hunk
dict
file
stringlengths
0
11.8M
file_path
stringlengths
2
234
label
int64
0
1
commit_url
stringlengths
74
103
dependency_score
sequencelengths
5
5
{ "id": 1, "code_window": [ " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " style ion-action-sheet fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-action-sheet\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 675 }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Toolbar - Translucent</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-header translucent> <ion-toolbar> <ion-title>Toolbar - Translucent</ion-title> </ion-toolbar> </ion-header> <ion-content fullscreen> <ion-grid> <ion-row> <ion-col size="6"> <f class="red"></f> </ion-col> <ion-col size="6"> <f class="green"></f> </ion-col> <ion-col size="6"> <f class="blue"></f> </ion-col> <ion-col size="6"> <f class="yellow"></f> </ion-col> <ion-col size="6"> <f class="pink"></f> </ion-col> <ion-col size="6"> <f class="purple"></f> </ion-col> <ion-col size="6"> <f class="black"></f> </ion-col> <ion-col size="6"> <f class="orange"></f> </ion-col> </ion-row> </ion-grid> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vitae lobortis felis, eu sodales enim. Nam risus nibh, placerat at rutrum ac, vehicula vel velit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum quis elementum ligula, ac aliquet nulla. Mauris non placerat mauris. Aenean dignissim lacinia porttitor. Praesent fringilla at est et ullamcorper. In ac ante ac massa porta venenatis ut id nibh. Fusce felis neque, aliquet in velit vitae, venenatis euismod libero. Donec vulputate, urna sed sagittis tempor, mi arcu tristique lacus, eget fringilla urna sem eget felis. Fusce dignissim lacus a scelerisque vehicula. Nulla nec enim nunc. Quisque nec dui eu nibh pulvinar bibendum quis ut nunc. Duis ex odio, sollicitudin ac mollis nec, fringilla non lacus. Maecenas sed tincidunt urna. Nunc feugiat maximus venenatis. Donec porttitor, felis eget porttitor tempor, quam nulla dapibus nisl, sit amet posuere sapien sapien malesuada tortor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque luctus, sapien nec tincidunt efficitur, nibh turpis faucibus felis, in sodales massa augue nec erat. Morbi sollicitudin nisi ex, et gravida nisi euismod eu. Suspendisse hendrerit dapibus orci, non viverra neque vestibulum id. Quisque vitae interdum ligula, quis consectetur nibh. Phasellus in mi at erat ultrices semper. Fusce sollicitudin at dolor ac lobortis. Morbi sit amet sem quis nulla pellentesque imperdiet. Nullam eu sem a enim maximus eleifend non vulputate leo. Proin quis congue lacus. Pellentesque placerat, quam at tempus pulvinar, nisl ligula tempor risus, quis pretium arcu odio et nulla. Nullam mollis consequat pharetra. Phasellus dictum velit sed purus mattis maximus. In molestie eget massa ut dignissim. In a interdum elit. In finibus nibh a mauris lobortis aliquet. Proin rutrum varius consequat. In mollis dapibus nisl, eu finibus urna viverra ac. Quisque scelerisque nisl eu suscipit consectetur. </p> <ion-grid> <ion-row> <ion-col size="6"> <f class="red"></f> </ion-col> <ion-col size="6"> <f class="green"></f> </ion-col> <ion-col size="6"> <f class="blue"></f> </ion-col> <ion-col size="6"> <f class="yellow"></f> </ion-col> <ion-col size="6"> <f class="pink"></f> </ion-col> <ion-col size="6"> <f class="purple"></f> </ion-col> <ion-col size="6"> <f class="black"></f> </ion-col> <ion-col size="6"> <f class="orange"></f> </ion-col> </ion-row> </ion-grid> </ion-content> <ion-footer translucent> <ion-toolbar> <ion-title>Toolbar - Translucent</ion-title> </ion-toolbar> </ion-footer> </ion-app> <style> f { display: block; height: 200px; } .red { background-color: #ea445a; } .green { background-color: #76d672; } .blue { background-color: #3478f6; } .yellow { background-color: #ffff80; } .pink { background-color: #ff6b86; } .purple { background-color: #7e34f6; } .black { background-color: #000; } .orange { background-color: #f69234; } </style> </body> </html>
core/src/components/toolbar/test/translucent/index.html
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0001775334239937365, 0.00016936629253905267, 0.00016518635675311089, 0.00016866461373865604, 0.0000032554582958255196 ]
{ "id": 1, "code_window": [ " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " style ion-action-sheet fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-action-sheet\n" ], "file_path": "core/src/components/action-sheet/readme.md", "type": "add", "edit_start_line_idx": 675 }
```tsx import React, { useState } from 'react'; import { IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonInput, IonItem, IonLabel, IonList, IonItemDivider } from '@ionic/react'; export const InputExamples: React.FC = () => { const [text, setText] = useState<string>(); const [number, setNumber] = useState<number>(); return ( <IonPage> <IonHeader> <IonToolbar> <IonTitle>IonInput Examples</IonTitle> </IonToolbar> </IonHeader> <IonContent> <IonList> <IonItemDivider>Default Input with Placeholder</IonItemDivider> <IonItem> <IonInput value={text} placeholder="Enter Input" onIonChange={e => setText(e.detail.value!)}></IonInput> </IonItem> <IonItemDivider>Input with clear button when there is a value</IonItemDivider> <IonItem> <IonInput value={text} placeholder="Enter Input" onIonChange={e => setText(e.detail.value!)} clearInput></IonInput> </IonItem> <IonItemDivider>Number type input</IonItemDivider> <IonItem> <IonInput type="number" value={number} placeholder="Enter Number" onIonChange={e => setNumber(parseInt(e.detail.value!, 10))}></IonInput> </IonItem> <IonItemDivider>Disabled input</IonItemDivider> <IonItem> <IonInput value={text} disabled></IonInput> </IonItem> <IonItemDivider>Readonly input</IonItemDivider> <IonItem> <IonInput value={text} readonly></IonInput> </IonItem> <IonItemDivider>Inputs with labels</IonItemDivider> <IonItem> <IonLabel>Default Label</IonLabel> <IonInput></IonInput> </IonItem> <IonItem> <IonLabel position="floating">Floating Label</IonLabel> <IonInput value={text}></IonInput> </IonItem> <IonItem> <IonLabel position="fixed">Fixed Label</IonLabel> <IonInput value={text}></IonInput> </IonItem> <IonItem> <IonLabel position="stacked">Stacked Label</IonLabel> <IonInput value={text}> </IonInput> </IonItem> </IonList> </IonContent> </IonPage> ); }; ```
core/src/components/input/usage/react.md
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0002992837689816952, 0.00018800044199451804, 0.00016591185703873634, 0.00017294577264692634, 0.00004216625893604942 ]
{ "id": 2, "code_window": [ "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-ripple-effect](../ripple-effect)\n", "- [ion-backdrop](../backdrop)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1000 }
# ion-select Selects are form controls to select an option, or options, from a set of options, similar to a native `<select>` element. When a user taps the select, a dialog appears with all of the options in a large, easy to select list. A select should be used with child `<ion-select-option>` elements. If the child option is not given a `value` attribute then its text will be used as the value. If `value` is set on the `<ion-select>`, the selected option will be chosen based on that value. ## Interfaces By default, select uses [ion-alert](../alert) to open up the overlay of options in an alert. The interface can be changed to use [ion-action-sheet](../action-sheet) or [ion-popover](../popover) by passing `action-sheet` or `popover`, respectively, to the `interface` property. Read on to the other sections for the limitations of the different interfaces. ## Single Selection By default, the select allows the user to select only one option. The alert interface presents users with a radio button styled list of options. The action sheet interface can only be used with a single value select. The select component's value receives the value of the selected option's value. ## Multiple Selection By adding the `multiple` attribute to select, users are able to select multiple options. When multiple options can be selected, the alert overlay presents users with a checkbox styled list of options. The select component's value receives an array of all of the selected option values. Note: the `action-sheet` and `popover` interfaces will not work with multiple selection. ## Object Value References When using objects for select values, it is possible for the identities of these objects to change if they are coming from a server or database, while the selected value's identity remains the same. For example, this can occur when an existing record with the desired object value is loaded into the select, but the newly retrieved select options now have different identities. This will result in the select appearing to have no value at all, even though the original selection in still intact. By default, the select uses object equality (`===`) to determine if an option is selected. This can be overridden by providing a property name or a function to the `compareWith` property. ## Select Buttons The alert supports two buttons: `Cancel` and `OK`. Each button's text can be customized using the `cancelText` and `okText` properties. The `action-sheet` and `popover` interfaces do not have an `OK` button, clicking on any of the options will automatically close the overlay and select that value. The `popover` interface does not have a `Cancel` button, clicking on the backdrop will close the overlay. ## Interface Options Since select uses the alert, action sheet and popover interfaces, options can be passed to these components through the `interfaceOptions` property. This can be used to pass a custom header, subheader, css class, and more. See the [ion-alert docs](../alert), [ion-action-sheet docs](../action-sheet), and [ion-popover docs](../popover) for the properties that each interface accepts. Note: `interfaceOptions` will not override `inputs` or `buttons` with the `alert` interface. ## Customization There are two units that make up the Select component and each need to be styled separately. The `ion-select` element is represented on the view by the selected value(s), or placeholder if there is none, and dropdown icon. The interface, which is defined in the [Interfaces](#interfaces) section above, is the dialog that opens when clicking on the `ion-select`. The interface contains all of the options defined by adding `ion-select-option` elements. The following sections will go over the differences between styling these. ### Styling Select Element As mentioned, the `ion-select` element consists only of the value(s), or placeholder, and icon that is displayed on the view. To customize this, style using a combination of CSS and any of the [CSS custom properties](#css-custom-properties): ```css ion-select { /* Applies to the value and placeholder color */ color: #545ca7; /* Set a different placeholder color */ --placeholder-color: #971e49; /* Set full opacity on the placeholder */ --placeholder-opacity: 1; } ``` Alternatively, depending on the [browser support](https://caniuse.com/#feat=mdn-css_selectors_part) needed, CSS shadow parts can be used to style the select: ```css /* Set the width to the full container and center the content */ ion-select { width: 100%; justify-content: center; } /* Set the flex in order to size the text width to its content */ ion-select::part(placeholder), ion-select::part(text) { flex: 0 0 auto; } /* Set the placeholder color and opacity */ ion-select::part(placeholder) { color: #20a08a; opacity: 1; } /* * Set the font of the first letter of the placeholder * Shadow parts work with pseudo-elements, too! * https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements */ ion-select::part(placeholder)::first-letter { font-size: 24px; font-weight: 500; } /* Set the text color */ ion-select::part(text) { color: #545ca7; } /* Set the icon color and opacity */ ion-select::part(icon) { color: #971e49; opacity: 1; } ``` Notice that by using `::part`, any CSS property on the element can be targeted. ### Styling Select Interface Customizing the interface dialog should be done by following the Customization section in that interface's documentation: - [Alert Customization](../alert#customization) - [Action Sheet Customization](../action-sheet#customization) - [Popover Customization](../popover#customization) However, the Select Option does set a class for easier styling and allows for the ability to pass a class to the overlay option, see the [Select Options documentation](../select-option) for usage examples of customizing options. ## Interfaces ### SelectChangeEventDetail ```typescript interface SelectChangeEventDetail<T = any> { value: T; } ``` ### SelectCustomEvent While not required, this interface can be used in place of the `CustomEvent` interface for stronger typing with Ionic events emitted from this component. ```typescript interface SelectCustomEvent<T = any> extends CustomEvent { detail: SelectChangeEventDetail<T>; target: HTMLIonSelectElement; } ``` <!-- Auto Generated Below --> ## Usage ### Angular ### Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" [value]="['bird', 'dog']"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith"> <ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; interface User { id: number; first: string; last: string; } @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: User[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith(o1: User, o2: User) { return o1 && o2 ? o1.id === o2.id : o1 === o2; } } ``` ### Objects as Values with Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith" multiple="true"> <ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; interface User { id: number; first: string; last: string; } @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: User[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith(o1: User, o2: User | User[]) { if (!o1 || !o2) { return o1 === o2; } if (Array.isArray(o2)) { return o2.some((u: User) => u.id === o1.id); } return o1.id === o2.id; } } ``` ### Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select [interfaceOptions]="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select [interfaceOptions]="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; } ``` ### Javascript ### Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancel-text="Nah" ok-text="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select id="multiple" multiple="true"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```javascript const select = document.querySelector('multiple'); select.value = ['bird', 'dog']; ``` ### Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select id="objectSelectCompareWith"></ion-select> </ion-item> </ion-list> ``` ```javascript let objectOptions = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; let compareWithFn = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; let objectSelectElement = document.getElementById('objectSelectCompareWith'); objectSelectElement.compareWith = compareWithFn; objectOptions.forEach((option, i) => { let selectOption = document.createElement('ion-select-option'); selectOption.value = option; selectOption.textContent = option.first + ' ' + option.last; objectSelectElement.appendChild(selectOption) }); objectSelectElement.value = objectOptions[0]; } ``` ### Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select id="customAlertSelect" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select id="customPopoverSelect" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select id="customActionSheetSelect" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```javascript var customAlertSelect = document.getElementById('customAlertSelect'); var customAlertOptions = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customAlertSelect.interfaceOptions = customAlertOptions; var customPopoverSelect = document.getElementById('customPopoverSelect'); var customPopoverOptions = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customPopoverSelect.interfaceOptions = customPopoverOptions; var customActionSheetSelect = document.getElementById('customActionSheetSelect'); var customActionSheetOptions = { header: 'Colors', subHeader: 'Select your favorite color' }; customActionSheetSelect.interfaceOptions = customActionSheetOptions; ``` ### React ### Single Selection ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; export const SingleSelection: React.FC = () => { const [gender, setGender] = useState<string>(); const [hairColor, setHairColor] = useState<string>('brown'); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Single Selection </IonLabel> </IonListHeader> <IonItem> <IonLabel>Gender</IonLabel> <IonSelect value={gender} placeholder="Select One" onIonChange={e => setGender(e.detail.value)}> <IonSelectOption value="female">Female</IonSelectOption> <IonSelectOption value="male">Male</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Hair Color</IonLabel> <IonSelect value={hairColor} okText="Okay" cancelText="Dismiss" onIonChange={e => setHairColor(e.detail.value)}> <IonSelectOption value="brown">Brown</IonSelectOption> <IonSelectOption value="blonde">Blonde</IonSelectOption> <IonSelectOption value="black">Black</IonSelectOption> <IonSelectOption value="red">Red</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Gender: {gender ?? '(none selected)'}</IonItem> <IonItem>Hair Color: {hairColor}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Multiple Selection ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; export const MultipleSelection: React.FC = () => { const [toppings, setToppings] = useState<string[]>([]); const [pets, setPets] = useState<string[]>(['bird', 'dog']); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Multiple Selection </IonLabel> </IonListHeader> <IonItem> <IonLabel>Toppings</IonLabel> <IonSelect value={toppings} multiple={true} cancelText="Nah" okText="Okay!" onIonChange={e => setToppings(e.detail.value)}> <IonSelectOption value="bacon">Bacon</IonSelectOption> <IonSelectOption value="olives">Black Olives</IonSelectOption> <IonSelectOption value="xcheese">Extra Cheese</IonSelectOption> <IonSelectOption value="peppers">Green Peppers</IonSelectOption> <IonSelectOption value="mushrooms">Mushrooms</IonSelectOption> <IonSelectOption value="onions">Onions</IonSelectOption> <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption> <IonSelectOption value="pineapple">Pineapple</IonSelectOption> <IonSelectOption value="sausage">Sausage</IonSelectOption> <IonSelectOption value="Spinach">Spinach</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Pets</IonLabel> <IonSelect multiple={true} value={pets} onIonChange={e => setPets(e.detail.value)}> <IonSelectOption value="bird">Bird</IonSelectOption> <IonSelectOption value="cat">Cat</IonSelectOption> <IonSelectOption value="dog">Dog</IonSelectOption> <IonSelectOption value="honeybadger">Honey Badger</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Toppings: {toppings.length ? toppings.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> <IonItem>Pets: {pets.length ? pets.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Objects as Values ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; const users = [ { id: 1, first: 'Alice', last: 'Smith' }, { id: 2, first: 'Bob', last: 'Davis' }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; type User = typeof users[number]; const compareWith = (o1: User, o2: User) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; export const ObjectSelection: React.FC = () => { const [selectedUsers, setSelectedUsers] = useState<User[]>([]); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Objects as Values (compareWith) </IonLabel> </IonListHeader> <IonItem> <IonLabel>Users</IonLabel> <IonSelect compareWith={compareWith} value={selectedUsers} multiple onIonChange={e => setSelectedUsers(e.detail.value)}> {users.map(user => ( <IonSelectOption key={user.id} value={user}> {user.first} {user.last} </IonSelectOption> ))} </IonSelect> </IonItem> <IonItemDivider>Selected Users</IonItemDivider> {selectedUsers.length ? selectedUsers.map(user => <IonItem key={user.id}>{user.first} {user.last}</IonItem>) : <IonItem>(none selected)</IonItem> } </IonList> </IonContent> </IonPage> ); }; ``` ### Interface Options ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; const customAlertOptions = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; const customPopoverOptions = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; const customActionSheetOptions = { header: 'Colors', subHeader: 'Select your favorite color' }; export const InterfaceOptionsSelection: React.FC = () => { const [toppings, setToppings] = useState<string[]>([]); const [hairColor, setHairColor] = useState<string>('brown'); const [color, setColor] = useState<string>(); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Interface Options </IonLabel> </IonListHeader> <IonItem> <IonLabel>Alert</IonLabel> <IonSelect interfaceOptions={customAlertOptions} interface="alert" multiple={true} placeholder="Select One" onIonChange={e => setToppings(e.detail.value)} value={toppings} > <IonSelectOption value="bacon">Bacon</IonSelectOption> <IonSelectOption value="olives">Black Olives</IonSelectOption> <IonSelectOption value="xcheese">Extra Cheese</IonSelectOption> <IonSelectOption value="peppers">Green Peppers</IonSelectOption> <IonSelectOption value="mushrooms">Mushrooms</IonSelectOption> <IonSelectOption value="onions">Onions</IonSelectOption> <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption> <IonSelectOption value="pineapple">Pineapple</IonSelectOption> <IonSelectOption value="sausage">Sausage</IonSelectOption> <IonSelectOption value="Spinach">Spinach</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Popover</IonLabel> <IonSelect interfaceOptions={customPopoverOptions} interface="popover" placeholder="Select One" onIonChange={e => setHairColor(e.detail.value)} value={hairColor}> <IonSelectOption value="brown">Brown</IonSelectOption> <IonSelectOption value="blonde">Blonde</IonSelectOption> <IonSelectOption value="black">Black</IonSelectOption> <IonSelectOption value="red">Red</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Action Sheet</IonLabel> <IonSelect interfaceOptions={customActionSheetOptions} interface="action-sheet" placeholder="Select One" onIonChange={e => setColor(e.detail.value)} value={color} > <IonSelectOption value="red">Red</IonSelectOption> <IonSelectOption value="purple">Purple</IonSelectOption> <IonSelectOption value="yellow">Yellow</IonSelectOption> <IonSelectOption value="orange">Orange</IonSelectOption> <IonSelectOption value="green">Green</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Toppings: {toppings.length ? toppings.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> <IonItem>Hair Color: {hairColor}</IonItem> <IonItem>Color: {color ?? '(none selected)'}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Stencil ### Single Selection ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { render() { return [ <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Multiple Selection ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { render() { return [ <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple={true} cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple={true} value={['bird', 'dog']}> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Objects as Values ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { private users: any[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; render() { return [ <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select compareWith={this.compareWith}> {this.users.map(user => <ion-select-option value={user}> {user.first + ' ' + user.last} </ion-select-option> )} </ion-select> </ion-item> </ion-list> ]; } } ``` ### Interface Options ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { private customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; private customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; private customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; render() { return [ <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select interfaceOptions={this.customAlertOptions} interface="alert" multiple={true} placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select interfaceOptions={this.customPopoverOptions} interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select interfaceOptions={this.customActionSheetOptions} interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Vue ### Single Selection ```html <template> <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } }); </script> ``` ### Multiple Selection ```html <template> <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancel-text="Nah" ok-text="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" :value=['bird', 'dog']> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } }); </script> ``` ### Interface Options ```html <template> <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select :interface-options="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select :interface-options="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select :interface-options="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption }, setup() { const customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; const customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; const customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; return { customAlertOptions, customPopoverOptions, customActionSheetOptions } } }); </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ------------------ | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------- | | `cancelText` | `cancel-text` | The text to display on the cancel button. | `string` | `'Cancel'` | | `compareWith` | `compare-with` | A property name or function used to compare object values | `((currentValue: any, compareValue: any) => boolean) \| null \| string \| undefined` | `undefined` | | `disabled` | `disabled` | If `true`, the user cannot interact with the select. | `boolean` | `false` | | `interface` | `interface` | The interface the select should use: `action-sheet`, `popover` or `alert`. | `"action-sheet" \| "alert" \| "popover"` | `'alert'` | | `interfaceOptions` | `interface-options` | Any additional options that the `alert`, `action-sheet` or `popover` interface can take. See the [ion-alert docs](../alert), the [ion-action-sheet docs](../action-sheet) and the [ion-popover docs](../popover) for the create options for each interface. Note: `interfaceOptions` will not override `inputs` or `buttons` with the `alert` interface. | `any` | `{}` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `multiple` | `multiple` | If `true`, the select can accept multiple values. | `boolean` | `false` | | `name` | `name` | The name of the control, which is submitted with the form data. | `string` | `this.inputId` | | `okText` | `ok-text` | The text to display on the ok button. | `string` | `'OK'` | | `placeholder` | `placeholder` | The text to display when the select is empty. | `string \| undefined` | `undefined` | | `selectedText` | `selected-text` | The text to display instead of the selected option's value. | `null \| string \| undefined` | `undefined` | | `value` | `value` | the value of the select. | `any` | `undefined` | ## Events | Event | Description | Type | | ----------- | ---------------------------------------- | ------------------------------------------- | | `ionBlur` | Emitted when the select loses focus. | `CustomEvent<void>` | | `ionCancel` | Emitted when the selection is cancelled. | `CustomEvent<void>` | | `ionChange` | Emitted when the value has changed. | `CustomEvent<SelectChangeEventDetail<any>>` | | `ionFocus` | Emitted when the select has focus. | `CustomEvent<void>` | ## Methods ### `open(event?: UIEvent | undefined) => Promise<any>` Open the select overlay. The overlay is either an alert, action sheet, or popover, depending on the `interface` property on the `ion-select`. #### Returns Type: `Promise<any>` ## Shadow Parts | Part | Description | | --------------- | -------------------------------------------------------- | | `"icon"` | The select icon container. | | `"placeholder"` | The text displayed in the select when there is no value. | | `"text"` | The displayed value of the select. | ## CSS Custom Properties | Name | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------- | | `--padding-bottom` | Bottom padding of the select | | `--padding-end` | Right padding if direction is left-to-right, and left padding if direction is right-to-left of the select | | `--padding-start` | Left padding if direction is left-to-right, and right padding if direction is right-to-left of the select | | `--padding-top` | Top padding of the select | | `--placeholder-color` | Color of the select placeholder text | | `--placeholder-opacity` | Opacity of the select placeholder text | ## Dependencies ### Depends on - ion-select-popover ### Graph ```mermaid graph TD; ion-select --> ion-select-popover ion-select-popover --> ion-item ion-select-popover --> ion-checkbox ion-select-popover --> ion-label ion-select-popover --> ion-radio-group ion-select-popover --> ion-radio ion-select-popover --> ion-list ion-select-popover --> ion-list-header ion-item --> ion-icon ion-item --> ion-ripple-effect ion-item --> ion-note style ion-select fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/select/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0024439122062176466, 0.00027441137353889644, 0.00016626469732727855, 0.00021950990776531398, 0.00026384112425148487 ]
{ "id": 2, "code_window": [ "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-ripple-effect](../ripple-effect)\n", "- [ion-backdrop](../backdrop)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1000 }
@import "../../themes/ionic.globals"; // Item Divider // -------------------------------------------------- /// @prop - Minimum height for the divider $item-divider-min-height: 30px !default;
core/src/components/item-divider/item-divider.vars.scss
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00016794586554169655, 0.00016794586554169655, 0.00016794586554169655, 0.00016794586554169655, 0 ]
{ "id": 2, "code_window": [ "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-ripple-effect](../ripple-effect)\n", "- [ion-backdrop](../backdrop)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1000 }
import { JSXBase } from '@stencil/core/internal'; import { AnimationBuilder, Mode } from '../../interface'; export interface PickerOptions { columns: PickerColumn[]; buttons?: PickerButton[]; cssClass?: string | string[]; showBackdrop?: boolean; backdropDismiss?: boolean; animated?: boolean; mode?: Mode; keyboardClose?: boolean; id?: string; htmlAttributes?: PickerAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; } export interface PickerAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} export interface PickerButton { text?: string; role?: string; cssClass?: string | string[]; handler?: (value: any) => boolean | void; } export interface PickerColumn { name: string; align?: string; selectedIndex?: number; prevSelected?: number; prefix?: string; suffix?: string; options: PickerColumnOption[]; cssClass?: string | string[]; columnWidth?: string; prefixWidth?: string; suffixWidth?: string; optionsWidth?: string; refresh?: () => void; } export interface PickerColumnOption { text?: string; value?: any; disabled?: boolean; duration?: number; transform?: string; selected?: boolean; }
core/src/components/picker/picker-interface.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.000251440069405362, 0.0001850283588282764, 0.00016968768613878638, 0.00017231218225788325, 0.00002972714719362557 ]
{ "id": 2, "code_window": [ "\n", "## Dependencies\n", "\n", "### Depends on\n", "\n", "- [ion-ripple-effect](../ripple-effect)\n", "- [ion-backdrop](../backdrop)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "### Used by\n", "\n", " - [ion-select](../select)\n", "\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1000 }
pushd ../../.. # Build core pushd core npm run build npm link popd # Build angular pushd angular npm link @ionic/core npm run build npm link popd # Build angular-server pushd packages/angular-server npm link @ionic/core npm link @ionic/angular npm run build popd popd
angular/test/test-app/scripts/build-ionic.sh
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017240560555364937, 0.00017054496856871992, 0.00016850230167619884, 0.0001707270130282268, 0.0000015987076267265365 ]
{ "id": 3, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n", " style ion-alert fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-alert\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1010 }
# ion-action-sheet An Action Sheet is a dialog that displays a set of options. It appears on top of the app's content, and must be manually dismissed by the user before they can resume interaction with the app. Destructive options are made obvious in `ios` mode. There are multiple ways to dismiss the action sheet, including tapping the backdrop or hitting the escape key on desktop. ## Buttons A button's `role` property can either be `destructive` or `cancel`. Buttons without a role property will have the default look for the platform. Buttons with the `cancel` role will always load as the bottom button, no matter where they are in the array. All other buttons will be displayed in the order they have been added to the `buttons` array. Note: We recommend that `destructive` buttons are always the first button in the array, making them the top button. Additionally, if the action sheet is dismissed by tapping the backdrop, then it will fire the handler from the button with the cancel role. A button can also be passed data via the `data` property on `ActionSheetButton`. This will populate the `data` field in the return value of the `onDidDismiss` method. ## Customization Action Sheet uses scoped encapsulation, which means it will automatically scope its CSS by appending each of the styles with an additional class at runtime. Overriding scoped selectors in CSS requires a [higher specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) selector. We recommend passing a custom class to `cssClass` in the `create` method and using that to add custom styles to the host and inner elements. This property can also accept multiple classes separated by spaces. View the [Usage](#usage) section for an example of how to pass a class using `cssClass`. ```css /* DOES NOT WORK - not specific enough */ .action-sheet-group { background: #e5e5e5; } /* Works - pass "my-custom-class" in cssClass to increase specificity */ .my-custom-class .action-sheet-group { background: #e5e5e5; } ``` Any of the defined [CSS Custom Properties](#css-custom-properties) can be used to style the Action Sheet without needing to target individual elements: ```css .my-custom-class { --background: #e5e5e5; } ``` > If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information. ## Interfaces ### ActionSheetButton ```typescript interface ActionSheetButton<T = any> { text?: string; role?: 'cancel' | 'destructive' | 'selected' | string; icon?: string; cssClass?: string | string[]; handler?: () => boolean | void | Promise<boolean | void>; data?: T; } ``` ### ActionSheetOptions ```typescript interface ActionSheetOptions { header?: string; subHeader?: string; cssClass?: string | string[]; buttons: (ActionSheetButton | string)[]; backdropDismiss?: boolean; translucent?: boolean; animated?: boolean; mode?: Mode; keyboardClose?: boolean; id?: string; htmlAttributes?: ActionSheetAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; } ``` ### ActionSheetAttributes ```typescript interface ActionSheetAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} ``` <!-- Auto Generated Below --> ## Usage ### Angular ```typescript import { Component } from '@angular/core'; import { ActionSheetController } from '@ionic/angular'; @Component({ selector: 'action-sheet-example', templateUrl: 'action-sheet-example.html', styleUrls: ['./action-sheet-example.css'], }) export class ActionSheetExample { constructor(public actionSheetController: ActionSheetController) {} async presentActionSheet() { const actionSheet = await this.actionSheetController.create({ header: 'Albums', cssClass: 'my-custom-class', buttons: [{ text: 'Delete', role: 'destructive', icon: 'trash', id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: 'share', data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: 'caret-forward-circle', data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: 'heart', handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: 'close', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }] }); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); } } ``` ### Style Placement In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Action Sheet can be presented from within a page, the `ion-action-sheet` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config). ### Javascript ```javascript async function presentActionSheet() { const actionSheet = document.createElement('ion-action-sheet'); actionSheet.header = 'Albums'; actionSheet.cssClass = 'my-custom-class'; actionSheet.buttons = [{ text: 'Delete', role: 'destructive', icon: 'trash', id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: 'share', data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: 'caret-forward-circle', data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: 'heart', handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: 'close', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }]; document.body.appendChild(actionSheet); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); } ``` ### React ```tsx /* Using with useIonActionSheet Hook */ import React from 'react'; import { IonButton, IonContent, IonPage, useIonActionSheet, } from '@ionic/react'; const ActionSheetExample: React.FC = () => { const [present, dismiss] = useIonActionSheet(); return ( <IonPage> <IonContent> <IonButton expand="block" onClick={() => present({ buttons: [{ text: 'Ok' }, { text: 'Cancel' }], header: 'Action Sheet' }) } > Show ActionSheet </IonButton> <IonButton expand="block" onClick={() => present([{ text: 'Ok' }, { text: 'Cancel' }], 'Action Sheet') } > Show ActionSheet using params </IonButton> <IonButton expand="block" onClick={() => { present([{ text: 'Ok' }, { text: 'Cancel' }], 'Action Sheet'); setTimeout(dismiss, 3000); }} > Show ActionSheet, hide after 3 seconds </IonButton> </IonContent> </IonPage> ); }; ``` ```tsx /* Using with IonActionSheet Component */ import React, { useState } from 'react'; import { IonActionSheet, IonContent, IonButton } from '@ionic/react'; import { trash, share, caretForwardCircle, heart, close } from 'ionicons/icons'; export const ActionSheetExample: React.FC = () => { const [showActionSheet, setShowActionSheet] = useState(false); return ( <IonContent> <IonButton onClick={() => setShowActionSheet(true)} expand="block"> Show Action Sheet </IonButton> <IonActionSheet isOpen={showActionSheet} onDidDismiss={() => setShowActionSheet(false)} cssClass='my-custom-class' buttons={[{ text: 'Delete', role: 'destructive', icon: trash, id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: share, data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: caretForwardCircle, data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: heart, handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: close, role: 'cancel', handler: () => { console.log('Cancel clicked'); } }]} > </IonActionSheet> </IonContent> ); } ``` ### Stencil ```tsx import { Component, h } from '@stencil/core'; import { actionSheetController } from '@ionic/core'; @Component({ tag: 'action-sheet-example', styleUrl: 'action-sheet-example.css' }) export class ActionSheetExample { async presentActionSheet() { const actionSheet = await actionSheetController.create({ header: 'Albums', cssClass: 'my-custom-class', buttons: [{ text: 'Delete', role: 'destructive', icon: 'trash', id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: 'share', data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: 'caret-forward-circle', data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: 'heart', handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: 'close', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }] }); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); } render() { return [ <ion-content> <ion-button onClick={() => this.presentActionSheet()}>Present Action Sheet</ion-button> </ion-content> ]; } } ``` ### Vue ```html <template> <ion-button @click="presentActionSheet">Show Action Sheet</ion-button> </template> <script> import { IonButton, actionSheetController } from '@ionic/vue'; import { defineComponent } from 'vue'; import { caretForwardCircle, close, heart, trash, share } from 'ionicons/icons'; export default defineComponent({ components: { IonButton }, methods: { async presentActionSheet() { const actionSheet = await actionSheetController .create({ header: 'Albums', cssClass: 'my-custom-class', buttons: [ { text: 'Delete', role: 'destructive', icon: trash, id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked') }, }, { text: 'Share', icon: share, data: 10, handler: () => { console.log('Share clicked') }, }, { text: 'Play (open modal)', icon: caretForwardCircle, data: 'Data value', handler: () => { console.log('Play clicked') }, }, { text: 'Favorite', icon: heart, handler: () => { console.log('Favorite clicked') }, }, { text: 'Cancel', icon: close, role: 'cancel', handler: () => { console.log('Cancel clicked') }, }, ], }); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); }, }, }); </script> ``` Developers can also use this component directly in their template: ```html <template> <ion-button @click="setOpen(true)">Show Action Sheet</ion-button> <ion-action-sheet :is-open="isOpenRef" header="Albums" css-class="my-custom-class" :buttons="buttons" @didDismiss="setOpen(false)" > </ion-action-sheet> </template> <script> import { IonActionSheet, IonButton } from '@ionic/vue'; import { defineComponent, ref } from 'vue'; import { caretForwardCircle, close, heart, trash, share } from 'ionicons/icons'; export default defineComponent({ components: { IonActionSheet, IonButton }, setup() { const isOpenRef = ref(false); const setOpen = (state: boolean) => isOpenRef.value = state; const buttons = [ { text: 'Delete', role: 'destructive', icon: trash, data: { type: 'delete' } handler: () => { console.log('Delete clicked') }, }, { text: 'Share', icon: share, data: 10, handler: () => { console.log('Share clicked') }, }, { text: 'Play (open modal)', icon: caretForwardCircle, data: 'Data value', handler: () => { console.log('Play clicked') }, }, { text: 'Favorite', icon: heart, handler: () => { console.log('Favorite clicked') }, }, { text: 'Cancel', icon: close, role: 'cancel', handler: () => { console.log('Cancel clicked') }, }, ]; return { buttons, isOpenRef, setOpen } } }); </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ----------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ----------- | | `animated` | `animated` | If `true`, the action sheet will animate. | `boolean` | `true` | | `backdropDismiss` | `backdrop-dismiss` | If `true`, the action sheet will be dismissed when the backdrop is clicked. | `boolean` | `true` | | `buttons` | -- | An array of buttons for the action sheet. | `(string \| ActionSheetButton<any>)[]` | `[]` | | `cssClass` | `css-class` | Additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces. | `string \| string[] \| undefined` | `undefined` | | `enterAnimation` | -- | Animation to use when the action sheet is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `header` | `header` | Title for the action sheet. | `string \| undefined` | `undefined` | | `htmlAttributes` | -- | Additional attributes to pass to the action sheet. | `ActionSheetAttributes \| undefined` | `undefined` | | `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` | | `leaveAnimation` | -- | Animation to use when the action sheet is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `subHeader` | `sub-header` | Subtitle for the action sheet. | `string \| undefined` | `undefined` | | `translucent` | `translucent` | If `true`, the action sheet will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` | ## Events | Event | Description | Type | | --------------------------- | --------------------------------------- | -------------------------------------- | | `ionActionSheetDidDismiss` | Emitted after the alert has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionActionSheetDidPresent` | Emitted after the alert has presented. | `CustomEvent<void>` | | `ionActionSheetWillDismiss` | Emitted before the alert has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionActionSheetWillPresent` | Emitted before the alert has presented. | `CustomEvent<void>` | ## Methods ### `dismiss(data?: any, role?: string | undefined) => Promise<boolean>` Dismiss the action sheet overlay after it has been presented. #### Returns Type: `Promise<boolean>` ### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the action sheet did dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the action sheet will dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `present() => Promise<void>` Present the action sheet overlay after it has been created. #### Returns Type: `Promise<void>` ## CSS Custom Properties | Name | Description | | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `--backdrop-opacity` | Opacity of the backdrop | | `--background` | Background of the action sheet group | | `--button-background` | Background of the action sheet button | | `--button-background-activated` | Background of the action sheet button when pressed. Note: setting this will interfere with the Material Design ripple. | | `--button-background-activated-opacity` | Opacity of the action sheet button background when pressed | | `--button-background-focused` | Background of the action sheet button when tabbed to | | `--button-background-focused-opacity` | Opacity of the action sheet button background when tabbed to | | `--button-background-hover` | Background of the action sheet button on hover | | `--button-background-hover-opacity` | Opacity of the action sheet button background on hover | | `--button-background-selected` | Background of the selected action sheet button | | `--button-background-selected-opacity` | Opacity of the selected action sheet button background | | `--button-color` | Color of the action sheet button | | `--button-color-activated` | Color of the action sheet button when pressed | | `--button-color-focused` | Color of the action sheet button when tabbed to | | `--button-color-hover` | Color of the action sheet button on hover | | `--button-color-selected` | Color of the selected action sheet button | | `--color` | Color of the action sheet text | | `--height` | height of the action sheet | | `--max-height` | Maximum height of the action sheet | | `--max-width` | Maximum width of the action sheet | | `--min-height` | Minimum height of the action sheet | | `--min-width` | Minimum width of the action sheet | | `--width` | Width of the action sheet | ## Dependencies ### Depends on - [ion-backdrop](../backdrop) - ion-icon - [ion-ripple-effect](../ripple-effect) ### Graph ```mermaid graph TD; ion-action-sheet --> ion-backdrop ion-action-sheet --> ion-icon ion-action-sheet --> ion-ripple-effect style ion-action-sheet fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/action-sheet/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.046451881527900696, 0.0008968859328888357, 0.0001647476601647213, 0.0001723817695165053, 0.00553098926320672 ]
{ "id": 3, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n", " style ion-alert fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-alert\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1010 }
import { ComponentFactoryResolver, Injector, Injectable } from '@angular/core'; import { PopoverOptions, popoverController } from '@ionic/core'; import { OverlayBaseController } from '../util/overlay'; import { AngularDelegate } from './angular-delegate'; @Injectable() export class PopoverController extends OverlayBaseController<PopoverOptions, HTMLIonPopoverElement> { constructor( private angularDelegate: AngularDelegate, private resolver: ComponentFactoryResolver, private injector: Injector ) { super(popoverController); } create(opts: PopoverOptions): Promise<HTMLIonPopoverElement> { return super.create({ ...opts, delegate: this.angularDelegate.create(this.resolver, this.injector), }); } }
angular/src/providers/popover-controller.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017186085460707545, 0.0001680143759585917, 0.00016407731163781136, 0.00016810494707897305, 0.0000031782633413968142 ]
{ "id": 3, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n", " style ion-alert fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-alert\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1010 }
```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'segment-button-example', styleUrl: 'segment-button-example.css' }) export class SegmentButtonExample { segmentChanged(ev: any) { console.log('Segment changed', ev); } render() { return [ // Segment buttons with text and click listener <ion-segment onIonChange={(ev) => this.segmentChanged(ev)}> <ion-segment-button> <ion-label>Friends</ion-label> </ion-segment-button> <ion-segment-button> <ion-label>Enemies</ion-label> </ion-segment-button> </ion-segment>, // Segment buttons with the first checked and the last disabled <ion-segment value="paid"> <ion-segment-button value="paid"> <ion-label>Paid</ion-label> </ion-segment-button> <ion-segment-button value="free"> <ion-label>Free</ion-label> </ion-segment-button> <ion-segment-button disabled value="top"> <ion-label>Top</ion-label> </ion-segment-button> </ion-segment>, // Segment buttons with values and icons <ion-segment> <ion-segment-button value="camera"> <ion-icon name="camera"></ion-icon> </ion-segment-button> <ion-segment-button value="bookmark"> <ion-icon name="bookmark"></ion-icon> </ion-segment-button> </ion-segment>, // Segment with a value that checks the last button <ion-segment value="shared"> <ion-segment-button value="bookmarks"> <ion-label>Bookmarks</ion-label> </ion-segment-button> <ion-segment-button value="reading"> <ion-label>Reading List</ion-label> </ion-segment-button> <ion-segment-button value="shared"> <ion-label>Shared Links</ion-label> </ion-segment-button> </ion-segment>, // Label only <ion-segment value="1"> <ion-segment-button value="1"> <ion-label>Item One</ion-label> </ion-segment-button> <ion-segment-button value="2"> <ion-label>Item Two</ion-label> </ion-segment-button> <ion-segment-button value="3"> <ion-label>Item Three</ion-label> </ion-segment-button> </ion-segment>, // Icon only <ion-segment value="heart"> <ion-segment-button value="call"> <ion-icon name="call"></ion-icon> </ion-segment-button> <ion-segment-button value="heart"> <ion-icon name="heart"></ion-icon> </ion-segment-button> <ion-segment-button value="pin"> <ion-icon name="pin"></ion-icon> </ion-segment-button> </ion-segment>, // Icon top <ion-segment value="2"> <ion-segment-button value="1"> <ion-label>Item One</ion-label> <ion-icon name="call"></ion-icon> </ion-segment-button> <ion-segment-button value="2"> <ion-label>Item Two</ion-label> <ion-icon name="heart"></ion-icon> </ion-segment-button> <ion-segment-button value="3"> <ion-label>Item Three</ion-label> <ion-icon name="pin"></ion-icon> </ion-segment-button> </ion-segment>, // Icon bottom <ion-segment value="1"> <ion-segment-button value="1" layout="icon-bottom"> <ion-icon name="call"></ion-icon> <ion-label>Item One</ion-label> </ion-segment-button> <ion-segment-button value="2" layout="icon-bottom"> <ion-icon name="heart"></ion-icon> <ion-label>Item Two</ion-label> </ion-segment-button> <ion-segment-button value="3" layout="icon-bottom"> <ion-icon name="pin"></ion-icon> <ion-label>Item Three</ion-label> </ion-segment-button> </ion-segment>, // Icon start <ion-segment value="1"> <ion-segment-button value="1" layout="icon-start"> <ion-label>Item One</ion-label> <ion-icon name="call"></ion-icon> </ion-segment-button> <ion-segment-button value="2" layout="icon-start"> <ion-label>Item Two</ion-label> <ion-icon name="heart"></ion-icon> </ion-segment-button> <ion-segment-button value="3" layout="icon-start"> <ion-label>Item Three</ion-label> <ion-icon name="pin"></ion-icon> </ion-segment-button> </ion-segment>, // Icon end <ion-segment value="1"> <ion-segment-button value="1" layout="icon-end"> <ion-icon name="call"></ion-icon> <ion-label>Item One</ion-label> </ion-segment-button> <ion-segment-button value="2" disabled layout="icon-end"> <ion-icon name="heart"></ion-icon> <ion-label>Item Two</ion-label> </ion-segment-button> <ion-segment-button value="3" layout="icon-end"> <ion-icon name="pin"></ion-icon> <ion-label>Item Three</ion-label> </ion-segment-button> </ion-segment> ]; } } ```
core/src/components/segment-button/usage/stencil.md
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00018196293967776, 0.00016813710681162775, 0.000163652774062939, 0.00016651267651468515, 0.000004520425591181265 ]
{ "id": 3, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n", " style ion-alert fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-alert\n" ], "file_path": "core/src/components/alert/readme.md", "type": "add", "edit_start_line_idx": 1010 }
/** * Toolbar * ----------------------------------------------------- * The toolbar theme customizes the toolbar only * * Looking to create a custom theme? Check out the generator! * https://ionicframework.com/docs/theming/color-generator **/ :root { --ion-color-primary: #3880ff; --ion-color-light: #f4f5f8; --ion-color-light-rgb: 244, 245, 248; --ion-toolbar-background: var(--ion-color-primary); --ion-toolbar-color: var(--ion-color-light); } .md body { --ion-toolbar-segment-color: rgba(var(--ion-color-light-rgb), .7); --ion-toolbar-segment-color-checked: var(--ion-color-light); } .ios body { --ion-toolbar-segment-color-checked: var(--ion-color-primary); }
core/src/themes/test/css-variables/css/toolbar.css
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0001706788461888209, 0.00016780740406829864, 0.00016448959650006145, 0.00016825376951601356, 0.000002546387577240239 ]
{ "id": 4, "code_window": [ "### Used by\n", "\n", " - [ion-datetime](../datetime)\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " - [ion-select](../select)\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1000 }
# ion-action-sheet An Action Sheet is a dialog that displays a set of options. It appears on top of the app's content, and must be manually dismissed by the user before they can resume interaction with the app. Destructive options are made obvious in `ios` mode. There are multiple ways to dismiss the action sheet, including tapping the backdrop or hitting the escape key on desktop. ## Buttons A button's `role` property can either be `destructive` or `cancel`. Buttons without a role property will have the default look for the platform. Buttons with the `cancel` role will always load as the bottom button, no matter where they are in the array. All other buttons will be displayed in the order they have been added to the `buttons` array. Note: We recommend that `destructive` buttons are always the first button in the array, making them the top button. Additionally, if the action sheet is dismissed by tapping the backdrop, then it will fire the handler from the button with the cancel role. A button can also be passed data via the `data` property on `ActionSheetButton`. This will populate the `data` field in the return value of the `onDidDismiss` method. ## Customization Action Sheet uses scoped encapsulation, which means it will automatically scope its CSS by appending each of the styles with an additional class at runtime. Overriding scoped selectors in CSS requires a [higher specificity](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity) selector. We recommend passing a custom class to `cssClass` in the `create` method and using that to add custom styles to the host and inner elements. This property can also accept multiple classes separated by spaces. View the [Usage](#usage) section for an example of how to pass a class using `cssClass`. ```css /* DOES NOT WORK - not specific enough */ .action-sheet-group { background: #e5e5e5; } /* Works - pass "my-custom-class" in cssClass to increase specificity */ .my-custom-class .action-sheet-group { background: #e5e5e5; } ``` Any of the defined [CSS Custom Properties](#css-custom-properties) can be used to style the Action Sheet without needing to target individual elements: ```css .my-custom-class { --background: #e5e5e5; } ``` > If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information. ## Interfaces ### ActionSheetButton ```typescript interface ActionSheetButton<T = any> { text?: string; role?: 'cancel' | 'destructive' | 'selected' | string; icon?: string; cssClass?: string | string[]; handler?: () => boolean | void | Promise<boolean | void>; data?: T; } ``` ### ActionSheetOptions ```typescript interface ActionSheetOptions { header?: string; subHeader?: string; cssClass?: string | string[]; buttons: (ActionSheetButton | string)[]; backdropDismiss?: boolean; translucent?: boolean; animated?: boolean; mode?: Mode; keyboardClose?: boolean; id?: string; htmlAttributes?: ActionSheetAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; } ``` ### ActionSheetAttributes ```typescript interface ActionSheetAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} ``` <!-- Auto Generated Below --> ## Usage ### Angular ```typescript import { Component } from '@angular/core'; import { ActionSheetController } from '@ionic/angular'; @Component({ selector: 'action-sheet-example', templateUrl: 'action-sheet-example.html', styleUrls: ['./action-sheet-example.css'], }) export class ActionSheetExample { constructor(public actionSheetController: ActionSheetController) {} async presentActionSheet() { const actionSheet = await this.actionSheetController.create({ header: 'Albums', cssClass: 'my-custom-class', buttons: [{ text: 'Delete', role: 'destructive', icon: 'trash', id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: 'share', data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: 'caret-forward-circle', data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: 'heart', handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: 'close', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }] }); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); } } ``` ### Style Placement In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Action Sheet can be presented from within a page, the `ion-action-sheet` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config). ### Javascript ```javascript async function presentActionSheet() { const actionSheet = document.createElement('ion-action-sheet'); actionSheet.header = 'Albums'; actionSheet.cssClass = 'my-custom-class'; actionSheet.buttons = [{ text: 'Delete', role: 'destructive', icon: 'trash', id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: 'share', data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: 'caret-forward-circle', data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: 'heart', handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: 'close', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }]; document.body.appendChild(actionSheet); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); } ``` ### React ```tsx /* Using with useIonActionSheet Hook */ import React from 'react'; import { IonButton, IonContent, IonPage, useIonActionSheet, } from '@ionic/react'; const ActionSheetExample: React.FC = () => { const [present, dismiss] = useIonActionSheet(); return ( <IonPage> <IonContent> <IonButton expand="block" onClick={() => present({ buttons: [{ text: 'Ok' }, { text: 'Cancel' }], header: 'Action Sheet' }) } > Show ActionSheet </IonButton> <IonButton expand="block" onClick={() => present([{ text: 'Ok' }, { text: 'Cancel' }], 'Action Sheet') } > Show ActionSheet using params </IonButton> <IonButton expand="block" onClick={() => { present([{ text: 'Ok' }, { text: 'Cancel' }], 'Action Sheet'); setTimeout(dismiss, 3000); }} > Show ActionSheet, hide after 3 seconds </IonButton> </IonContent> </IonPage> ); }; ``` ```tsx /* Using with IonActionSheet Component */ import React, { useState } from 'react'; import { IonActionSheet, IonContent, IonButton } from '@ionic/react'; import { trash, share, caretForwardCircle, heart, close } from 'ionicons/icons'; export const ActionSheetExample: React.FC = () => { const [showActionSheet, setShowActionSheet] = useState(false); return ( <IonContent> <IonButton onClick={() => setShowActionSheet(true)} expand="block"> Show Action Sheet </IonButton> <IonActionSheet isOpen={showActionSheet} onDidDismiss={() => setShowActionSheet(false)} cssClass='my-custom-class' buttons={[{ text: 'Delete', role: 'destructive', icon: trash, id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: share, data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: caretForwardCircle, data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: heart, handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: close, role: 'cancel', handler: () => { console.log('Cancel clicked'); } }]} > </IonActionSheet> </IonContent> ); } ``` ### Stencil ```tsx import { Component, h } from '@stencil/core'; import { actionSheetController } from '@ionic/core'; @Component({ tag: 'action-sheet-example', styleUrl: 'action-sheet-example.css' }) export class ActionSheetExample { async presentActionSheet() { const actionSheet = await actionSheetController.create({ header: 'Albums', cssClass: 'my-custom-class', buttons: [{ text: 'Delete', role: 'destructive', icon: 'trash', id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked'); } }, { text: 'Share', icon: 'share', data: 10, handler: () => { console.log('Share clicked'); } }, { text: 'Play (open modal)', icon: 'caret-forward-circle', data: 'Data value', handler: () => { console.log('Play clicked'); } }, { text: 'Favorite', icon: 'heart', handler: () => { console.log('Favorite clicked'); } }, { text: 'Cancel', icon: 'close', role: 'cancel', handler: () => { console.log('Cancel clicked'); } }] }); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); } render() { return [ <ion-content> <ion-button onClick={() => this.presentActionSheet()}>Present Action Sheet</ion-button> </ion-content> ]; } } ``` ### Vue ```html <template> <ion-button @click="presentActionSheet">Show Action Sheet</ion-button> </template> <script> import { IonButton, actionSheetController } from '@ionic/vue'; import { defineComponent } from 'vue'; import { caretForwardCircle, close, heart, trash, share } from 'ionicons/icons'; export default defineComponent({ components: { IonButton }, methods: { async presentActionSheet() { const actionSheet = await actionSheetController .create({ header: 'Albums', cssClass: 'my-custom-class', buttons: [ { text: 'Delete', role: 'destructive', icon: trash, id: 'delete-button', data: { type: 'delete' }, handler: () => { console.log('Delete clicked') }, }, { text: 'Share', icon: share, data: 10, handler: () => { console.log('Share clicked') }, }, { text: 'Play (open modal)', icon: caretForwardCircle, data: 'Data value', handler: () => { console.log('Play clicked') }, }, { text: 'Favorite', icon: heart, handler: () => { console.log('Favorite clicked') }, }, { text: 'Cancel', icon: close, role: 'cancel', handler: () => { console.log('Cancel clicked') }, }, ], }); await actionSheet.present(); const { role, data } = await actionSheet.onDidDismiss(); console.log('onDidDismiss resolved with role and data', role, data); }, }, }); </script> ``` Developers can also use this component directly in their template: ```html <template> <ion-button @click="setOpen(true)">Show Action Sheet</ion-button> <ion-action-sheet :is-open="isOpenRef" header="Albums" css-class="my-custom-class" :buttons="buttons" @didDismiss="setOpen(false)" > </ion-action-sheet> </template> <script> import { IonActionSheet, IonButton } from '@ionic/vue'; import { defineComponent, ref } from 'vue'; import { caretForwardCircle, close, heart, trash, share } from 'ionicons/icons'; export default defineComponent({ components: { IonActionSheet, IonButton }, setup() { const isOpenRef = ref(false); const setOpen = (state: boolean) => isOpenRef.value = state; const buttons = [ { text: 'Delete', role: 'destructive', icon: trash, data: { type: 'delete' } handler: () => { console.log('Delete clicked') }, }, { text: 'Share', icon: share, data: 10, handler: () => { console.log('Share clicked') }, }, { text: 'Play (open modal)', icon: caretForwardCircle, data: 'Data value', handler: () => { console.log('Play clicked') }, }, { text: 'Favorite', icon: heart, handler: () => { console.log('Favorite clicked') }, }, { text: 'Cancel', icon: close, role: 'cancel', handler: () => { console.log('Cancel clicked') }, }, ]; return { buttons, isOpenRef, setOpen } } }); </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ----------------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- | ----------- | | `animated` | `animated` | If `true`, the action sheet will animate. | `boolean` | `true` | | `backdropDismiss` | `backdrop-dismiss` | If `true`, the action sheet will be dismissed when the backdrop is clicked. | `boolean` | `true` | | `buttons` | -- | An array of buttons for the action sheet. | `(string \| ActionSheetButton<any>)[]` | `[]` | | `cssClass` | `css-class` | Additional classes to apply for custom CSS. If multiple classes are provided they should be separated by spaces. | `string \| string[] \| undefined` | `undefined` | | `enterAnimation` | -- | Animation to use when the action sheet is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `header` | `header` | Title for the action sheet. | `string \| undefined` | `undefined` | | `htmlAttributes` | -- | Additional attributes to pass to the action sheet. | `ActionSheetAttributes \| undefined` | `undefined` | | `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` | | `leaveAnimation` | -- | Animation to use when the action sheet is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `subHeader` | `sub-header` | Subtitle for the action sheet. | `string \| undefined` | `undefined` | | `translucent` | `translucent` | If `true`, the action sheet will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` | ## Events | Event | Description | Type | | --------------------------- | --------------------------------------- | -------------------------------------- | | `ionActionSheetDidDismiss` | Emitted after the alert has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionActionSheetDidPresent` | Emitted after the alert has presented. | `CustomEvent<void>` | | `ionActionSheetWillDismiss` | Emitted before the alert has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionActionSheetWillPresent` | Emitted before the alert has presented. | `CustomEvent<void>` | ## Methods ### `dismiss(data?: any, role?: string | undefined) => Promise<boolean>` Dismiss the action sheet overlay after it has been presented. #### Returns Type: `Promise<boolean>` ### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the action sheet did dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the action sheet will dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `present() => Promise<void>` Present the action sheet overlay after it has been created. #### Returns Type: `Promise<void>` ## CSS Custom Properties | Name | Description | | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | | `--backdrop-opacity` | Opacity of the backdrop | | `--background` | Background of the action sheet group | | `--button-background` | Background of the action sheet button | | `--button-background-activated` | Background of the action sheet button when pressed. Note: setting this will interfere with the Material Design ripple. | | `--button-background-activated-opacity` | Opacity of the action sheet button background when pressed | | `--button-background-focused` | Background of the action sheet button when tabbed to | | `--button-background-focused-opacity` | Opacity of the action sheet button background when tabbed to | | `--button-background-hover` | Background of the action sheet button on hover | | `--button-background-hover-opacity` | Opacity of the action sheet button background on hover | | `--button-background-selected` | Background of the selected action sheet button | | `--button-background-selected-opacity` | Opacity of the selected action sheet button background | | `--button-color` | Color of the action sheet button | | `--button-color-activated` | Color of the action sheet button when pressed | | `--button-color-focused` | Color of the action sheet button when tabbed to | | `--button-color-hover` | Color of the action sheet button on hover | | `--button-color-selected` | Color of the selected action sheet button | | `--color` | Color of the action sheet text | | `--height` | height of the action sheet | | `--max-height` | Maximum height of the action sheet | | `--max-width` | Maximum width of the action sheet | | `--min-height` | Minimum height of the action sheet | | `--min-width` | Minimum width of the action sheet | | `--width` | Width of the action sheet | ## Dependencies ### Depends on - [ion-backdrop](../backdrop) - ion-icon - [ion-ripple-effect](../ripple-effect) ### Graph ```mermaid graph TD; ion-action-sheet --> ion-backdrop ion-action-sheet --> ion-icon ion-action-sheet --> ion-ripple-effect style ion-action-sheet fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/action-sheet/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.005633197724819183, 0.00036924146115779877, 0.00016503664664924145, 0.00017670064698904753, 0.0007813262636773288 ]
{ "id": 4, "code_window": [ "### Used by\n", "\n", " - [ion-datetime](../datetime)\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " - [ion-select](../select)\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1000 }
```html <ion-app> <ion-menu side="start" menu-id="first" content-id="main"> <ion-header> <ion-toolbar color="primary"> <ion-title>Start Menu</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> </ion-list> </ion-content> </ion-menu> <ion-menu side="start" menu-id="custom" class="my-custom-menu" content-id="main"> <ion-header> <ion-toolbar color="tertiary"> <ion-title>Custom Menu</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> </ion-list> </ion-content> </ion-menu> <ion-menu side="end" type="push" content-id="main"> <ion-header> <ion-toolbar color="danger"> <ion-title>End Menu</ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-list> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> <ion-item>Menu Item</ion-item> </ion-list> </ion-content> </ion-menu> <div class="ion-page" id="main"> <ion-header> <ion-toolbar> <ion-title>Menu - Basic</ion-title> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <ion-button expand="block" onclick="openFirst()">Open Start Menu</ion-button> <ion-button expand="block" onclick="openEnd()">Open End Menu</ion-button> <ion-button expand="block" onclick="openCustom()">Open Custom Menu</ion-button> </ion-content> </div> </ion-app> ``` ```javascript <script type="module"> import { menuController } from '@ionic/core'; window.menuController = menuController; </script> <script> function openFirst() { menuController.enable(true, 'first'); menuController.open('first'); } function openEnd() { menuController.open('end'); } function openCustom() { menuController.enable(true, 'custom'); menuController.open('custom'); } </script> ``` ```css .my-custom-menu { --width: 500px; } ```
core/src/components/menu/usage/javascript.md
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0012833867222070694, 0.0006116600707173347, 0.00016890330880414695, 0.0005449698655866086, 0.00037609331775456667 ]
{ "id": 4, "code_window": [ "### Used by\n", "\n", " - [ion-datetime](../datetime)\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " - [ion-select](../select)\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1000 }
import { Component, ComponentInterface, Host, Prop, h } from '@stencil/core'; import { config } from '../../global/config'; import { getIonMode } from '../../global/ionic-global'; import { Color } from '../../interface'; import { clamp } from '../../utils/helpers'; import { createColorClasses } from '../../utils/theme'; /** * @virtualProp {"ios" | "md"} mode - The mode determines which platform styles to use. * * @part progress - The progress bar that shows the current value when `type` is `"determinate"` and slides back and forth when `type` is `"indeterminate"`. * @part stream - The animated circles that appear while buffering. This only shows when `buffer` is set and `type` is `"determinate"`. * @part track - The track bar behind the progress bar. If the `buffer` property is set and `type` is `"determinate"` the track will be the * width of the `buffer` value. */ @Component({ tag: 'ion-progress-bar', styleUrls: { ios: 'progress-bar.ios.scss', md: 'progress-bar.md.scss' }, shadow: true }) export class ProgressBar implements ComponentInterface { /** * The state of the progress bar, based on if the time the process takes is known or not. * Default options are: `"determinate"` (no animation), `"indeterminate"` (animate from left to right). */ @Prop() type: 'determinate' | 'indeterminate' = 'determinate'; /** * If true, reverse the progress bar direction. */ @Prop() reversed = false; /** * The value determines how much of the active bar should display when the * `type` is `"determinate"`. * The value should be between [0, 1]. */ @Prop() value = 0; /** * If the buffer and value are smaller than 1, the buffer circles will show. * The buffer should be between [0, 1]. */ @Prop() buffer = 1; /** * The color to use from your application's color palette. * Default options are: `"primary"`, `"secondary"`, `"tertiary"`, `"success"`, `"warning"`, `"danger"`, `"light"`, `"medium"`, and `"dark"`. * For more information on colors, see [theming](/docs/theming/basics). */ @Prop({ reflect: true }) color?: Color; render() { const { color, type, reversed, value, buffer } = this; const paused = config.getBoolean('_testing'); const mode = getIonMode(this); return ( <Host role="progressbar" aria-valuenow={type === 'determinate' ? value : null} aria-valuemin="0" aria-valuemax="1" class={createColorClasses(color, { [mode]: true, [`progress-bar-${type}`]: true, 'progress-paused': paused, 'progress-bar-reversed': document.dir === 'rtl' ? !reversed : reversed })} > {type === 'indeterminate' ? renderIndeterminate() : renderProgress(value, buffer) } </Host> ); } } const renderIndeterminate = () => { return ( <div part="track" class="progress-buffer-bar"> <div class="indeterminate-bar-primary"><span part="progress" class="progress-indeterminate"></span></div> <div class="indeterminate-bar-secondary"><span part="progress" class="progress-indeterminate"></span></div> </div> ); }; const renderProgress = (value: number, buffer: number) => { const finalValue = clamp(0, value, 1); const finalBuffer = clamp(0, buffer, 1); return [ <div part="progress" class="progress" style={{ transform: `scaleX(${finalValue})` }}></div>, /** * Buffer circles with two container to move * the circles behind the buffer progress * with respecting the animation. * When finalBuffer === 1, we use display: none * instead of removing the element to avoid flickering. */ <div class={{ 'buffer-circles-container': true, 'ion-hide': finalBuffer === 1 }} style={{ transform: `translateX(${finalBuffer * 100}%)` }}> <div class="buffer-circles-container" style={{ transform: `translateX(-${finalBuffer * 100}%)` }}> <div part="stream" class="buffer-circles"></div> </div> </div>, <div part="track" class="progress-buffer-bar" style={{ transform: `scaleX(${finalBuffer})` }}></div>, ]; };
core/src/components/progress-bar/progress-bar.tsx
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0002642199688125402, 0.00019396199786569923, 0.0001670552883297205, 0.00017030070011969656, 0.00003573072172002867 ]
{ "id": 4, "code_window": [ "### Used by\n", "\n", " - [ion-datetime](../datetime)\n", "\n", "### Depends on\n", "\n", "- [ion-backdrop](../backdrop)\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " - [ion-select](../select)\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1000 }
```html <!-- Default Searchbar --> <ion-searchbar></ion-searchbar> <!-- Searchbar with cancel button always shown --> <ion-searchbar showCancelButton="always"></ion-searchbar> <!-- Searchbar with cancel button never shown --> <ion-searchbar showCancelButton="never"></ion-searchbar> <!-- Searchbar with cancel button shown on focus --> <ion-searchbar showCancelButton="focus"></ion-searchbar> <!-- Searchbar with danger color --> <ion-searchbar color="danger"></ion-searchbar> <!-- Searchbar with value --> <ion-searchbar value="Ionic"></ion-searchbar> <!-- Searchbar with telephone type --> <ion-searchbar type="tel"></ion-searchbar> <!-- Searchbar with numeric inputmode --> <ion-searchbar inputmode="numeric"></ion-searchbar> <!-- Searchbar disabled --> <ion-searchbar disabled="true"></ion-searchbar> <!-- Searchbar with a cancel button and custom cancel button text --> <ion-searchbar showCancelButton="focus" cancelButtonText="Custom Cancel"></ion-searchbar> <!-- Searchbar with a custom debounce --> <ion-searchbar debounce="500"></ion-searchbar> <!-- Animated Searchbar --> <ion-searchbar animated></ion-searchbar> <!-- Searchbar with a placeholder --> <ion-searchbar placeholder="Filter Schedules"></ion-searchbar> <!-- Searchbar in a Toolbar --> <ion-toolbar> <ion-searchbar></ion-searchbar> </ion-toolbar> ```
core/src/components/searchbar/usage/angular.md
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00045825893175788224, 0.0003734199272003025, 0.00030755711486563087, 0.00034769930061884224, 0.000059218658861937 ]
{ "id": 5, "code_window": [ "graph TD;\n", " ion-popover --> ion-backdrop\n", " ion-datetime --> ion-popover\n", " style ion-popover fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1010 }
# ion-popover A Popover is a dialog that appears on top of the current page. It can be used for anything, but generally it is used for overflow actions that don't fit in the navigation bar. There are two ways to use `ion-popover`: inline or via the `popoverController`. Each method comes with different considerations, so be sure to use the approach that best fits your use case. ## Inline Popovers `ion-popover` can be used by writing the component directly in your template. This reduces the number of handlers you need to wire up in order to present the popover. See [Usage](#usage) for an example of how to write a popover inline. When using `ion-popover` with Angular, React, or Vue, the component you pass in will be destroyed when the popover is dismissed. As this functionality is provided by the JavaScript framework, using `ion-popover` without a JavaScript framework will not destroy the component you passed in. If this is a needed functionality, we recommend using the `popoverController` instead. ### Angular Since the component you passed in needs to be created when the popover is presented and destroyed when the popover is dismissed, we are unable to project the content using `<ng-content>` internally. Instead, we use `<ng-container>` which expects an `<ng-template>` to be passed in. As a result, when passing in your component you will need to wrap it in an `<ng-template>`: ```html <ion-popover [isOpen]="isPopoverOpen"> <ng-template> <app-popover-content></app-popover-content> </ng-template> </ion-popover> ``` ### When to use Using a popover inline is useful when you do not want to explicitly wire up click events to open the popover. For example, you can use the `trigger` property to designate a button that should present the popover when clicked. You can also use the `trigger-action` property to customize whether the popover should be presented when the trigger is left clicked, right clicked, or hovered over. If you need fine grained control over when the popover is presented and dismissed, we recommend you use the `popoverController`. ## Controller Popovers `ion-popover` can also be presented programmatically by using the `popoverController` imported from Ionic Framework. This allows you to have complete control over when a popover is presented above and beyond the customization that inline popovers give you. See [Usage](#usage) for an example of how to use the `popoverController`. ### When to use We typically recommend that you write your popovers inline as it streamlines the amount of code in your application. You should only use the `popoverController` for complex use cases where writing a popover inline is impractical. When using a controller, your popover is not created ahead of time, so properties such as `trigger` and `trigger-action` are not applicable here. In addition, nested popovers are not compatible with the controller approach because the popover is automatically added to the root of your application when the `create` method is called. ## Styling Popovers are presented at the root of your application so they overlay your entire app. This behavior applies to both inline popovers and popovers presented from a controller. As a result, custom popover styles can not be scoped to a particular component as they will not apply to the popover. Instead, styles must be applied globally. For most developers, placing the custom styles in `global.css` is sufficient. > If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information. ## Triggers A trigger for an `ion-popover` is the element that will open a popover when interacted with. The interaction behavior can be customized by setting the `trigger-action` property. Note that `trigger-action="context-menu"` will prevent your system's default context menu from opening. View the [Usage](#usage) section for an example of how to use triggers. > Triggers are not applicable when using the `popoverController` because the `ion-popover` is not created ahead of time. ## Positioning ### Reference When presenting a popover, Ionic Framework needs a reference point to present the popover relative to. With `reference="event"`, the popover will be presented relative to the x-y coordinates of the pointer event that was dispatched on your trigger element. With `reference="trigger"`, the popover will be presented relative to the bounding box of your trigger element. ### Side Regardless of what you choose for your reference point, you can position a popover to the `top`, `right`, `left`, or `bottom` of your reference point by using the `side` property. You can also use the `start` or `end` values if you would like the side to switch based on LTR or RTL modes. ### Alignment The `alignment` property allows you to line up an edge of your popover with a corresponding edge on your trigger element. The exact edge that is used depends on the value of the `side` property. ### Offsets If you need finer grained control over the positioning of your popover you can use the `--offset-x` and `--offset-y` CSS Variables. For example, `--offset-x: 10px` will move your popover content to the right by `10px`. ## Sizing When making dropdown menus, you may want to have the width of the popover match the width of the trigger element. Doing this without knowing the trigger width ahead of time is tricky. You can set the `size` property to `'cover'` and Ionic Framework will ensure that the width of the popover matches the width of your trigger element. If you are using the `popoverController`, you must provide an event via the `event` option and Ionic Framework will use `event.target` as the reference element. ## Nested Popovers When using `ion-popover` inline, you can nested popovers to create nested dropdown menus. When doing this, only the backdrop on the first popover will appear so that the screen does not get progressively darker as you open more popovers. See the [Usage](./#usage) section for an example on how to write a nested popover. You can use the `dismissOnSelect` property to automatically close the popover when the popover content has been clicked. This behavior does not apply when clicking a trigger element for another popover. > Nested popovers cannot be created when using the `popoverController` because the popover is automatically added to the root of your application when the `create` method is called. ## Interfaces Below you will find all of the options available to you when using the `popoverController`. These options should be supplied when calling `popoverController.create()`. ```typescript interface PopoverOptions { component: any; componentProps?: { [key: string]: any }; showBackdrop?: boolean; backdropDismiss?: boolean; translucent?: boolean; cssClass?: string | string[]; event?: Event; animated?: boolean; mode?: 'ios' | 'md'; keyboardClose?: boolean; id?: string; htmlAttributes?: PopoverAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; size?: PopoverSize; dismissOnSelect?: boolean; reference?: PositionReference; side?: PositionSide; alignment?: PositionAlign; arrow?: boolean; } ``` ### PopoverAttributes ```typescript interface PopoverAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} ``` ## Types Below you will find all of the custom types for `ion-popover`: ```typescript type PopoverSize = 'cover' | 'auto'; type TriggerAction = 'click' | 'hover' | 'context-menu'; type PositionReference = 'trigger' | 'event'; type PositionSide = 'top' | 'right' | 'bottom' | 'left' | 'start' | 'end'; type PositionAlign = 'start' | 'center' | 'end'; ``` ## Accessibility ### Keyboard Navigation `ion-popover` has basic keyboard support for navigating between focusable elements inside of the popover. The following table details what each key does: | Key | Function | | ------------------ | ------------------------------------------------------------ | | `Tab` | Moves focus to the next focusable element. | | `Shift` + `Tab` | Moves focus to the previous focusable element. | | `Esc` | Closes the popover. | | `Space` or `Enter` | Clicks the focusable element. | `ion-popover` has full arrow key support for navigating between `ion-item` elements with the `button` property. The most common use case for this is as a dropdown menu in a desktop-focused application. In addition to the basic keyboard support, the following table details arrow key support for dropdown menus: | Key | Function | | ------------------ | -------------------------------------------------------------- | | `ArrowUp` | Moves focus to the previous focusable element. | | `ArrowDown` | Moves focus to the next focusable element. | | `Home` | Moves focus to the first focusable element. | | `End` | Moves focus to the last focusable element. | | `ArrowLeft` | When used in a child popover, closes the popover and returns focus to the parent popover. | | `Space`, `Enter`, and `ArrowRight` | When focusing a trigger element, opens the associated popover. | <!-- Auto Generated Below --> ## Usage ### Angular ### Inline Popover ```html <!-- Default --> <ion-popover [isOpen]="true"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- No Arrow --> <ion-popover [isOpen]="true" [arrow]="false"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" [dismissOnSelect]="true"> <ng-template> <ion-content> <ion-list> <ion-item [button]="true" [detail]="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item [button]="true" [detail]="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item [button]="true" [detail]="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" [dismissOnSelect]="true" side="end"> <ng-template> <ion-content> <ion-item [button]="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ng-template> </ion-popover> </ion-list> </ion-content> </ng-template> </ion-popover> ``` ### Popover Controller ```typescript import { Component } from '@angular/core'; import { PopoverController } from '@ionic/angular'; import { PopoverComponent } from '../../component/popover/popover.component'; @Component({ selector: 'popover-example', templateUrl: 'popover-example.html', styleUrls: ['./popover-example.css'] }) export class PopoverExample { constructor(public popoverController: PopoverController) {} async presentPopover(ev: any) { const popover = await this.popoverController.create({ component: PopoverComponent, cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } } ``` ### Style Placement In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Popover can be presented from within a page, the `ion-popover` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config). ### Javascript ### Inline Popover ```html <!-- Default --> <ion-popover is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover is-open="true" arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismiss-on-select="true"> <ion-content> <ion-list> <ion-item button="true" detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item button="true" detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item button="true" detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismiss-on-select="true" side="end"> <ion-content> <ion-item button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> ``` ### Using JavaScript ```javascript class PopoverExamplePage extends HTMLElement { constructor() { super(); } connectedCallback() { this.innerHTML = ` <ion-content> <ion-list> <ion-list-header><ion-label>Ionic</ion-label></ion-list-header> <ion-item button><ion-label>Item 0</ion-label></ion-item> <ion-item button><ion-label>Item 1</ion-label></ion-item> <ion-item button><ion-label>Item 2</ion-label></ion-item> <ion-item button><ion-label>Item 3</ion-label></ion-item> </ion-list> </ion-content> `; } } customElements.define('popover-example-page', PopoverExamplePage); async function presentPopover(ev) { const popover = Object.assign(document.createElement('ion-popover'), { component: 'popover-example-page', cssClass: 'my-custom-class', event: ev, translucent: true }); document.body.appendChild(popover); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } ``` ### React ### Inline Popover ```tsx import React, { useState } from 'react'; import { IonPopover, IonContent, IonItem, IonLabel, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { return ( <> {/* Default */} <IonPopover isOpen={true}> <IonContent>Popover Content</IonContent> </IonPopover> {/* No Arrow */} <IonPopover isOpen={true} arrow={false}> <IonContent>Popover Content</IonContent> </IonPopover> {/* Use a trigger */} <IonButton id="trigger-button">Click to open popover</IonButton> <IonPopover trigger="trigger-button"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Hover over trigger to open */} <IonButton id="hover-button">Hover to open popover</IonButton> <IonPopover trigger="hover-button" triggerAction="hover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Show popover above trigger */} <IonButton id="side-button">Click to open popover</IonButton> <IonPopover trigger="side-button" side="top"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Align popover to end of trigger */} <IonButton id="alignment-button">Click to open popover</IonButton> <IonPopover trigger="alignment-button" side="top" alignment="end"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover the same size as the trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" size="cover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover show relative to click coordinates rather than trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" reference="event"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Nested Popover */} <IonButton id="nested-button">Click to open popover</IonButton> <IonPopover trigger="nested-button" dismissOnSelect={true}> <IonContent> <ion-list> <IonItem button={true} detail={false}> <IonLabel>Option 1</IonLabel> </IonItem> <IonItem button={true} detail={false}> <IonLabel>Option 2</IonLabel> </IonItem> <IonItem button={true} detail={true} id="nested-trigger"> <IonLabel>Option 3</IonLabel> </IonItem> <IonPopover trigger="nested-trigger" dismissOnSelect={true} side="end"> <IonContent> <IonItem button={true}> <IonLabel>Nested Option</IonLabel> </IonItem> </IonContent> </IonPopover> </ion-list> </IonContent> </IonPopover> </> ); }; ``` ### Inline Popover with State ```tsx import React, { useState } from 'react'; import { IonPopover, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { const [popoverState, setShowPopover] = useState({ showPopover: false, event: undefined }); return ( <> <IonPopover cssClass='my-custom-class' event={popoverState.event} isOpen={popoverState.showPopover} onDidDismiss={() => setShowPopover({ showPopover: false, event: undefined })} > <p>This is popover content</p> </IonPopover> <IonButton onClick={ (e: any) => { e.persist(); setShowPopover({ showPopover: true, event: e }) }} > Show Popover </IonButton> </> ); }; ``` ### useIonPopover Hook > `useIonPopover` requires being a descendant of `<IonApp>`. If you need to use a popover outside of an `<IonApp>`, consider using the component method instead. ```tsx import React from 'react'; import { IonButton, IonContent, IonItem, IonList, IonListHeader, IonPage, useIonPopover, } from '@ionic/react'; const PopoverList: React.FC<{ onHide: () => void; }> = ({ onHide }) => ( <IonList> <IonListHeader>Ionic</IonListHeader> <IonItem button>Learn Ionic</IonItem> <IonItem button>Documentation</IonItem> <IonItem button>Showcase</IonItem> <IonItem button>GitHub Repo</IonItem> <IonItem lines="none" detail={false} button onClick={onHide}> Close </IonItem> </IonList> ); const PopoverExample: React.FC = () => { const [present, dismiss] = useIonPopover(PopoverList, { onHide: () => dismiss() }); return ( <IonPage> <IonContent> <IonButton expand="block" onClick={(e) => present({ event: e.nativeEvent, }) } > Show Popover </IonButton> </IonContent> </IonPage> ); }; ``` ### Stencil ### Inline Popover ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { render() { return [ <ion-content> {/* Default */} <ion-popover isOpen={true}> <ion-content>Popover Content</ion-content> </ion-popover> {/* No Arrow */} <ion-popover isOpen={true} arrow={false}> <ion-content>Popover Content</ion-content> </ion-popover> {/* Use a trigger */} <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Hover over trigger to open */} <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Show popover above trigger */} <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Align popover to end of trigger */} <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover the same size as the trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover show relative to click coordinates rather than trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Nested Popover */} <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismissOnSelect={true}> <ion-content> <ion-list> <ion-item button={true} detail={false}> <ion-label>Option 1</ion-label> </ion-item> <ion-item button={true} detail={false}> <ion-label>Option 2</ion-label> </ion-item> <ion-item button={true} detail={true} id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismissOnSelect={true} side="end"> <ion-content> <ion-item button={true}> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Popover Controller ```tsx import { Component, h } from '@stencil/core'; import { popoverController } from '@ionic/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { async presentPopover(ev: any) { const popover = await popoverController.create({ component: 'page-popover', cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } render() { return [ <ion-content> <ion-button onClick={(ev) => this.presentPopover(ev)}>Present Popover</ion-button> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Vue ### Inline Popover ```html <template> <!-- Default --> <ion-popover :is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover :is-open="true" :arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" :dismiss-on-select="true"> <ion-content> <ion-list> <ion-item :button="true" :detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item :button="true" :detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item :button="true" :detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" :dismiss-on-select="true" side="end"> <ion-content> <ion-item :button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </template> <script> import { IonButton, IonContent, IonItem, IonLabel, IonPopover } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonButton, IonContent, IonItem, IonLabel, IonPopover } }); </script> ``` ### Inline Popover with State ```html <template> <ion-button @click="setOpen(true, $event)">Show Popover</ion-button> <ion-popover :is-open="isOpenRef" css-class="my-custom-class" :event="event" :translucent="true" @didDismiss="setOpen(false)" > <Popover></Popover> </ion-popover> </template> <script> import { IonButton, IonPopover } from '@ionic/vue'; import { defineComponent, ref } from 'vue'; import Popover from './popover.vue'; export default defineComponent({ components: { IonButton, IonPopover, Popover }, setup() { const isOpenRef = ref(false); const event = ref(); const setOpen = (state: boolean, ev?: Event) => { event.value = ev; isOpenRef.value = state; } return { isOpenRef, setOpen, event } } }); </script> ``` ### Popover Controller ```html <template> <ion-content class="ion-padding"> Popover Content </ion-content> </template> <script> import { IonContent } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Popover', components: { IonContent } }); </script> ``` ```html <template> <ion-page> <ion-content class="ion-padding"> <ion-button @click="openPopover">Open Popover</ion-button> </ion-content> </ion-page> </template> <script> import { IonButton, IonContent, IonPage, popoverController } from '@ionic/vue'; import Popover from './popover.vue'; export default { components: { IonButton, IonContent, IonPage }, methods: { async openPopover(ev: Event) { const popover = await popoverController .create({ component: Popover, cssClass: 'my-custom-class', event: ev, translucent: true }) await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); }, }, } </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------- | | `alignment` | `alignment` | Describes how to align the popover content with the `reference` point. Defaults to `'center'` for `ios` mode, and `'start'` for `md` mode. | `"center" \| "end" \| "start" \| undefined` | `undefined` | | `animated` | `animated` | If `true`, the popover will animate. | `boolean` | `true` | | `arrow` | `arrow` | If `true`, the popover will display an arrow that points at the `reference` when running in `ios` mode on mobile. Does not apply in `md` mode or on desktop. | `boolean` | `true` | | `backdropDismiss` | `backdrop-dismiss` | If `true`, the popover will be dismissed when the backdrop is clicked. | `boolean` | `true` | | `component` | `component` | The component to display inside of the popover. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just slot your component inside of `ion-popover`. | `Function \| HTMLElement \| null \| string \| undefined` | `undefined` | | `componentProps` | -- | The data to pass to the popover component. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just set the props directly on your component. | `undefined \| { [key: string]: any; }` | `undefined` | | `dismissOnSelect` | `dismiss-on-select` | If `true`, the popover will be automatically dismissed when the content has been clicked. | `boolean` | `false` | | `enterAnimation` | -- | Animation to use when the popover is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `event` | `event` | The event to pass to the popover animation. | `any` | `undefined` | | `htmlAttributes` | -- | Additional attributes to pass to the popover. | `PopoverAttributes \| undefined` | `undefined` | | `isOpen` | `is-open` | If `true`, the popover will open. If `false`, the popover will close. Use this if you need finer grained control over presentation, otherwise just use the popoverController or the `trigger` property. Note: `isOpen` will not automatically be set back to `false` when the popover dismisses. You will need to do that in your code. | `boolean` | `false` | | `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` | | `leaveAnimation` | -- | Animation to use when the popover is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `reference` | `reference` | Describes what to position the popover relative to. If `'trigger'`, the popover will be positioned relative to the trigger button. If passing in an event, this is determined via event.target. If `'event'`, the popover will be positioned relative to the x/y coordinates of the trigger action. If passing in an event, this is determined via event.clientX and event.clientY. | `"event" \| "trigger"` | `'trigger'` | | `showBackdrop` | `show-backdrop` | If `true`, a backdrop will be displayed behind the popover. | `boolean` | `true` | | `side` | `side` | Describes which side of the `reference` point to position the popover on. The `'start'` and `'end'` values are RTL-aware, and the `'left'` and `'right'` values are not. | `"bottom" \| "end" \| "left" \| "right" \| "start" \| "top"` | `'bottom'` | | `size` | `size` | Describes how to calculate the popover width. If `'cover'`, the popover width will match the width of the trigger. If `'auto'`, the popover width will be determined by the content in the popover. | `"auto" \| "cover"` | `'auto'` | | `translucent` | `translucent` | If `true`, the popover will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` | | `trigger` | `trigger` | An ID corresponding to the trigger element that causes the popover to open. Use the `trigger-action` property to customize the interaction that results in the popover opening. | `string \| undefined` | `undefined` | | `triggerAction` | `trigger-action` | Describes what kind of interaction with the trigger that should cause the popover to open. Does not apply when the `trigger` property is `undefined`. If `'click'`, the popover will be presented when the trigger is left clicked. If `'hover'`, the popover will be presented when a pointer hovers over the trigger. If `'context-menu'`, the popover will be presented when the trigger is right clicked on desktop and long pressed on mobile. This will also prevent your device's normal context menu from appearing. | `"click" \| "context-menu" \| "hover"` | `'click'` | ## Events | Event | Description | Type | | ----------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | | `didDismiss` | Emitted after the popover has dismissed. Shorthand for ionPopoverDidDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `didPresent` | Emitted after the popover has presented. Shorthand for ionPopoverWillDismiss. | `CustomEvent<void>` | | `ionPopoverDidDismiss` | Emitted after the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverDidPresent` | Emitted after the popover has presented. | `CustomEvent<void>` | | `ionPopoverWillDismiss` | Emitted before the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverWillPresent` | Emitted before the popover has presented. | `CustomEvent<void>` | | `willDismiss` | Emitted before the popover has dismissed. Shorthand for ionPopoverWillDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `willPresent` | Emitted before the popover has presented. Shorthand for ionPopoverWillPresent. | `CustomEvent<void>` | ## Methods ### `dismiss(data?: any, role?: string | undefined, dismissParentPopover?: boolean) => Promise<boolean>` Dismiss the popover overlay after it has been presented. #### Returns Type: `Promise<boolean>` ### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover did dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover will dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `present(event?: MouseEvent | TouchEvent | PointerEvent | CustomEvent<any> | undefined) => Promise<void>` Present the popover overlay after it has been created. Developers can pass a mouse, touch, or pointer event to position the popover relative to where that event was dispatched. #### Returns Type: `Promise<void>` ## Slots | Slot | Description | | ---- | ----------------------------------------------------------- | | | Content is placed inside of the `.popover-content` element. | ## Shadow Parts | Part | Description | | ------------ | --------------------------------------------------------------------------- | | `"arrow"` | The arrow that points to the reference element. Only applies on `ios` mode. | | `"backdrop"` | The `ion-backdrop` element. | | `"content"` | The wrapper element for the default slot. | ## CSS Custom Properties | Name | Description | | -------------------- | ----------------------------------------------- | | `--backdrop-opacity` | Opacity of the backdrop | | `--background` | Background of the popover | | `--box-shadow` | Box shadow of the popover | | `--height` | Height of the popover | | `--max-height` | Maximum height of the popover | | `--max-width` | Maximum width of the popover | | `--min-height` | Minimum height of the popover | | `--min-width` | Minimum width of the popover | | `--offset-x` | The amount to move the popover by on the x-axis | | `--offset-y` | The amount to move the popover by on the y-axis | | `--width` | Width of the popover | ## Dependencies ### Used by - [ion-datetime](../datetime) ### Depends on - [ion-backdrop](../backdrop) ### Graph ```mermaid graph TD; ion-popover --> ion-backdrop ion-datetime --> ion-popover style ion-popover fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/popover/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.9970741271972656, 0.010570387355983257, 0.00016348168719559908, 0.000398331816541031, 0.09459365159273148 ]
{ "id": 5, "code_window": [ "graph TD;\n", " ion-popover --> ion-backdrop\n", " ion-datetime --> ion-popover\n", " style ion-popover fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1010 }
```html <template> <ion-router> <ion-route url="/home" component="page-home"></ion-route> <ion-route url="/dashboard" component="page-dashboard" :beforeEnter="isLoggedInGuard"></ion-route> <ion-route url="/new-message" component="page-new-message" :beforeLeave="hasUnsavedDataGuard"></ion-route> <ion-route url="/login" component="page-login"></ion-route> </ion-router> </template> <script> import { alertController } from '@ionic/vue'; const isLoggedInGuard = async () => { const isLoggedIn = await UserData.isLoggedIn(); // Replace this with actual login validation if (isLoggedIn) { return true; } else { return { redirect: '/login' }; // If a user is not logged in, they will be redirected to the /login page } } const hasUnsavedDataGuard = async () => { const hasUnsavedData = await checkData(); // Replace this with actual validation if (hasUnsavedData) { return await confirmDiscardChanges(); } else { return true; } } const confirmDiscardChanges = async () => { const alert = await alertController.create({ header: 'Discard Unsaved Changes?', message: 'Are you sure you want to leave? Any unsaved changed will be lost.', buttons: [ { text: 'Cancel', role: 'Cancel', }, { text: 'Discard', role: 'destructive', } ] }); await alert.present(); const { role } = await alert.onDidDismiss(); return (role === 'Cancel') ? false : true; } </script> ```
core/src/components/route/usage/vue.md
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.002082440536469221, 0.0004888816620223224, 0.00016746181063354015, 0.00017081113765016198, 0.0007126625860109925 ]
{ "id": 5, "code_window": [ "graph TD;\n", " ion-popover --> ion-backdrop\n", " ion-datetime --> ion-popover\n", " style ion-popover fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1010 }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Thumbnail - Basic</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <body> <ion-app> <ion-header> <ion-toolbar> <ion-title>Thumbnail - Basic</ion-title> </ion-toolbar> </ion-header> <ion-content id="content"> <ion-thumbnail> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label>Item Thumbnail</ion-label> </ion-item> <ion-item> <ion-thumbnail slot="start"> <img src="/src/components/thumbnail/test/thumbnail.svg"> </ion-thumbnail> <ion-label>Wide Thumbnail</ion-label> </ion-item> </ion-content> </ion-app> </body> </html>
core/src/components/thumbnail/test/basic/index.html
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00021649120026268065, 0.00017890814342536032, 0.00016516493633389473, 0.00016739523562137038, 0.00001932688246597536 ]
{ "id": 5, "code_window": [ "graph TD;\n", " ion-popover --> ion-backdrop\n", " ion-datetime --> ion-popover\n", " style ion-popover fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n" ], "file_path": "core/src/components/popover/readme.md", "type": "add", "edit_start_line_idx": 1010 }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Refresher - Spec</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script></head> <style> ion-spinner { color: #555; } </style> <body> <ion-app> <ion-header> <ion-toolbar> <ion-buttons slot="start"> <ion-back-button default-href="/" text="Mailboxes"></ion-back-button> </ion-buttons> <ion-title>All Inboxes</ion-title> <ion-buttons slot="end"> <ion-button>Edit</ion-button> </ion-buttons> </ion-toolbar> </ion-header> <ion-content> <ion-refresher id="refresher" slot="fixed"> <ion-refresher-content></ion-refresher-content> </ion-refresher> <ion-header collapse="condense"> <ion-toolbar> <ion-title size="large">All Inboxes</ion-title> </ion-toolbar> <ion-toolbar> <ion-searchbar></ion-searchbar> </ion-toolbar> </ion-header> <ion-list id="list"></ion-list> <ion-fab vertical="bottom" horizontal="end" slot="fixed"> <ion-fab-button onclick="toggleHeader()"> <ion-icon name="settings"></ion-icon> </ion-fab-button> </ion-fab> </ion-content> </ion-app> <script> const toggleHeader = () => { const app = document.querySelector('ion-app'); const header = app.querySelector('ion-header'); if (header) { header.parentNode.removeChild(header); } else { app.insertAdjacentHTML("afterbegin", ` <ion-header> <ion-toolbar> <ion-buttons slot="start"> <ion-back-button default-href="/" text="Mailboxes"></ion-back-button> </ion-buttons> <ion-title>All Inboxes</ion-title> <ion-buttons slot="end"> <ion-button>Edit</ion-button> </ion-buttons> </ion-toolbar> </ion-header> `); } } let items = []; for (var i = 0; i < 30; i++) { items.push(i + 1); } const list = document.getElementById('list'); const refresher = document.getElementById('refresher'); refresher.addEventListener('ionPull', () => { console.log('ionPull'); }); refresher.addEventListener('ionStart', () => { console.log('ionStart'); }); refresher.addEventListener('ionRefresh', async function () { console.log('Loading data...'); const data = await getAsyncData(); items = items.concat(data); refresher.complete(); render(); console.log('Done'); }); function render() { let html = ''; for (let item of items) { html += `<ion-item button>${item}</ion-item>`; } list.innerHTML = html; } function getAsyncData() { // async return mock data return new Promise(resolve => { setTimeout(() => { let data = []; for (var i = 0; i < 30; i++) { data.push(i); } resolve(data); }, 5000); }); } render(); </script> </body> </html>
core/src/components/refresher/test/spec/index.html
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0004220855771563947, 0.00020489571033976972, 0.0001656824751989916, 0.00017234792176168412, 0.0000758255846449174 ]
{ "id": 6, "code_window": [ "\n", "### Depends on\n", "\n", "- ion-select-popover\n", "\n", "### Graph\n", "```mermaid\n", "graph TD;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [ion-popover](../popover)\n", "- [ion-action-sheet](../action-sheet)\n", "- [ion-alert](../alert)\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1000 }
# ion-select Selects are form controls to select an option, or options, from a set of options, similar to a native `<select>` element. When a user taps the select, a dialog appears with all of the options in a large, easy to select list. A select should be used with child `<ion-select-option>` elements. If the child option is not given a `value` attribute then its text will be used as the value. If `value` is set on the `<ion-select>`, the selected option will be chosen based on that value. ## Interfaces By default, select uses [ion-alert](../alert) to open up the overlay of options in an alert. The interface can be changed to use [ion-action-sheet](../action-sheet) or [ion-popover](../popover) by passing `action-sheet` or `popover`, respectively, to the `interface` property. Read on to the other sections for the limitations of the different interfaces. ## Single Selection By default, the select allows the user to select only one option. The alert interface presents users with a radio button styled list of options. The action sheet interface can only be used with a single value select. The select component's value receives the value of the selected option's value. ## Multiple Selection By adding the `multiple` attribute to select, users are able to select multiple options. When multiple options can be selected, the alert overlay presents users with a checkbox styled list of options. The select component's value receives an array of all of the selected option values. Note: the `action-sheet` and `popover` interfaces will not work with multiple selection. ## Object Value References When using objects for select values, it is possible for the identities of these objects to change if they are coming from a server or database, while the selected value's identity remains the same. For example, this can occur when an existing record with the desired object value is loaded into the select, but the newly retrieved select options now have different identities. This will result in the select appearing to have no value at all, even though the original selection in still intact. By default, the select uses object equality (`===`) to determine if an option is selected. This can be overridden by providing a property name or a function to the `compareWith` property. ## Select Buttons The alert supports two buttons: `Cancel` and `OK`. Each button's text can be customized using the `cancelText` and `okText` properties. The `action-sheet` and `popover` interfaces do not have an `OK` button, clicking on any of the options will automatically close the overlay and select that value. The `popover` interface does not have a `Cancel` button, clicking on the backdrop will close the overlay. ## Interface Options Since select uses the alert, action sheet and popover interfaces, options can be passed to these components through the `interfaceOptions` property. This can be used to pass a custom header, subheader, css class, and more. See the [ion-alert docs](../alert), [ion-action-sheet docs](../action-sheet), and [ion-popover docs](../popover) for the properties that each interface accepts. Note: `interfaceOptions` will not override `inputs` or `buttons` with the `alert` interface. ## Customization There are two units that make up the Select component and each need to be styled separately. The `ion-select` element is represented on the view by the selected value(s), or placeholder if there is none, and dropdown icon. The interface, which is defined in the [Interfaces](#interfaces) section above, is the dialog that opens when clicking on the `ion-select`. The interface contains all of the options defined by adding `ion-select-option` elements. The following sections will go over the differences between styling these. ### Styling Select Element As mentioned, the `ion-select` element consists only of the value(s), or placeholder, and icon that is displayed on the view. To customize this, style using a combination of CSS and any of the [CSS custom properties](#css-custom-properties): ```css ion-select { /* Applies to the value and placeholder color */ color: #545ca7; /* Set a different placeholder color */ --placeholder-color: #971e49; /* Set full opacity on the placeholder */ --placeholder-opacity: 1; } ``` Alternatively, depending on the [browser support](https://caniuse.com/#feat=mdn-css_selectors_part) needed, CSS shadow parts can be used to style the select: ```css /* Set the width to the full container and center the content */ ion-select { width: 100%; justify-content: center; } /* Set the flex in order to size the text width to its content */ ion-select::part(placeholder), ion-select::part(text) { flex: 0 0 auto; } /* Set the placeholder color and opacity */ ion-select::part(placeholder) { color: #20a08a; opacity: 1; } /* * Set the font of the first letter of the placeholder * Shadow parts work with pseudo-elements, too! * https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements */ ion-select::part(placeholder)::first-letter { font-size: 24px; font-weight: 500; } /* Set the text color */ ion-select::part(text) { color: #545ca7; } /* Set the icon color and opacity */ ion-select::part(icon) { color: #971e49; opacity: 1; } ``` Notice that by using `::part`, any CSS property on the element can be targeted. ### Styling Select Interface Customizing the interface dialog should be done by following the Customization section in that interface's documentation: - [Alert Customization](../alert#customization) - [Action Sheet Customization](../action-sheet#customization) - [Popover Customization](../popover#customization) However, the Select Option does set a class for easier styling and allows for the ability to pass a class to the overlay option, see the [Select Options documentation](../select-option) for usage examples of customizing options. ## Interfaces ### SelectChangeEventDetail ```typescript interface SelectChangeEventDetail<T = any> { value: T; } ``` ### SelectCustomEvent While not required, this interface can be used in place of the `CustomEvent` interface for stronger typing with Ionic events emitted from this component. ```typescript interface SelectCustomEvent<T = any> extends CustomEvent { detail: SelectChangeEventDetail<T>; target: HTMLIonSelectElement; } ``` <!-- Auto Generated Below --> ## Usage ### Angular ### Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" [value]="['bird', 'dog']"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith"> <ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; interface User { id: number; first: string; last: string; } @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: User[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith(o1: User, o2: User) { return o1 && o2 ? o1.id === o2.id : o1 === o2; } } ``` ### Objects as Values with Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select [compareWith]="compareWith" multiple="true"> <ion-select-option *ngFor="let user of users" [value]="user">{{user.first + ' ' + user.last}}</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; interface User { id: number; first: string; last: string; } @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { users: User[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith(o1: User, o2: User | User[]) { if (!o1 || !o2) { return o1 === o2; } if (Array.isArray(o2)) { return o2.some((u: User) => u.id === o1.id); } return o1.id === o2.id; } } ``` ### Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select [interfaceOptions]="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select [interfaceOptions]="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select [interfaceOptions]="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```typescript import { Component } from '@angular/core'; @Component({ selector: 'select-example', templateUrl: 'select-example.html', styleUrls: ['./select-example.css'], }) export class SelectExample { customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; } ``` ### Javascript ### Single Selection ```html <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ### Multiple Selection ```html <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancel-text="Nah" ok-text="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select id="multiple" multiple="true"> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```javascript const select = document.querySelector('multiple'); select.value = ['bird', 'dog']; ``` ### Objects as Values ```html <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select id="objectSelectCompareWith"></ion-select> </ion-item> </ion-list> ``` ```javascript let objectOptions = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; let compareWithFn = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; let objectSelectElement = document.getElementById('objectSelectCompareWith'); objectSelectElement.compareWith = compareWithFn; objectOptions.forEach((option, i) => { let selectOption = document.createElement('ion-select-option'); selectOption.value = option; selectOption.textContent = option.first + ' ' + option.last; objectSelectElement.appendChild(selectOption) }); objectSelectElement.value = objectOptions[0]; } ``` ### Interface Options ```html <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select id="customAlertSelect" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select id="customPopoverSelect" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select id="customActionSheetSelect" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ``` ```javascript var customAlertSelect = document.getElementById('customAlertSelect'); var customAlertOptions = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; customAlertSelect.interfaceOptions = customAlertOptions; var customPopoverSelect = document.getElementById('customPopoverSelect'); var customPopoverOptions = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; customPopoverSelect.interfaceOptions = customPopoverOptions; var customActionSheetSelect = document.getElementById('customActionSheetSelect'); var customActionSheetOptions = { header: 'Colors', subHeader: 'Select your favorite color' }; customActionSheetSelect.interfaceOptions = customActionSheetOptions; ``` ### React ### Single Selection ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; export const SingleSelection: React.FC = () => { const [gender, setGender] = useState<string>(); const [hairColor, setHairColor] = useState<string>('brown'); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Single Selection </IonLabel> </IonListHeader> <IonItem> <IonLabel>Gender</IonLabel> <IonSelect value={gender} placeholder="Select One" onIonChange={e => setGender(e.detail.value)}> <IonSelectOption value="female">Female</IonSelectOption> <IonSelectOption value="male">Male</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Hair Color</IonLabel> <IonSelect value={hairColor} okText="Okay" cancelText="Dismiss" onIonChange={e => setHairColor(e.detail.value)}> <IonSelectOption value="brown">Brown</IonSelectOption> <IonSelectOption value="blonde">Blonde</IonSelectOption> <IonSelectOption value="black">Black</IonSelectOption> <IonSelectOption value="red">Red</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Gender: {gender ?? '(none selected)'}</IonItem> <IonItem>Hair Color: {hairColor}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Multiple Selection ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; export const MultipleSelection: React.FC = () => { const [toppings, setToppings] = useState<string[]>([]); const [pets, setPets] = useState<string[]>(['bird', 'dog']); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Multiple Selection </IonLabel> </IonListHeader> <IonItem> <IonLabel>Toppings</IonLabel> <IonSelect value={toppings} multiple={true} cancelText="Nah" okText="Okay!" onIonChange={e => setToppings(e.detail.value)}> <IonSelectOption value="bacon">Bacon</IonSelectOption> <IonSelectOption value="olives">Black Olives</IonSelectOption> <IonSelectOption value="xcheese">Extra Cheese</IonSelectOption> <IonSelectOption value="peppers">Green Peppers</IonSelectOption> <IonSelectOption value="mushrooms">Mushrooms</IonSelectOption> <IonSelectOption value="onions">Onions</IonSelectOption> <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption> <IonSelectOption value="pineapple">Pineapple</IonSelectOption> <IonSelectOption value="sausage">Sausage</IonSelectOption> <IonSelectOption value="Spinach">Spinach</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Pets</IonLabel> <IonSelect multiple={true} value={pets} onIonChange={e => setPets(e.detail.value)}> <IonSelectOption value="bird">Bird</IonSelectOption> <IonSelectOption value="cat">Cat</IonSelectOption> <IonSelectOption value="dog">Dog</IonSelectOption> <IonSelectOption value="honeybadger">Honey Badger</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Toppings: {toppings.length ? toppings.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> <IonItem>Pets: {pets.length ? pets.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Objects as Values ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; const users = [ { id: 1, first: 'Alice', last: 'Smith' }, { id: 2, first: 'Bob', last: 'Davis' }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; type User = typeof users[number]; const compareWith = (o1: User, o2: User) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; export const ObjectSelection: React.FC = () => { const [selectedUsers, setSelectedUsers] = useState<User[]>([]); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Objects as Values (compareWith) </IonLabel> </IonListHeader> <IonItem> <IonLabel>Users</IonLabel> <IonSelect compareWith={compareWith} value={selectedUsers} multiple onIonChange={e => setSelectedUsers(e.detail.value)}> {users.map(user => ( <IonSelectOption key={user.id} value={user}> {user.first} {user.last} </IonSelectOption> ))} </IonSelect> </IonItem> <IonItemDivider>Selected Users</IonItemDivider> {selectedUsers.length ? selectedUsers.map(user => <IonItem key={user.id}>{user.first} {user.last}</IonItem>) : <IonItem>(none selected)</IonItem> } </IonList> </IonContent> </IonPage> ); }; ``` ### Interface Options ```tsx import React, { useState } from 'react'; import { IonContent, IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption, IonPage, IonItemDivider } from '@ionic/react'; const customAlertOptions = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; const customPopoverOptions = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; const customActionSheetOptions = { header: 'Colors', subHeader: 'Select your favorite color' }; export const InterfaceOptionsSelection: React.FC = () => { const [toppings, setToppings] = useState<string[]>([]); const [hairColor, setHairColor] = useState<string>('brown'); const [color, setColor] = useState<string>(); return ( <IonPage> <IonContent> <IonList> <IonListHeader> <IonLabel> Interface Options </IonLabel> </IonListHeader> <IonItem> <IonLabel>Alert</IonLabel> <IonSelect interfaceOptions={customAlertOptions} interface="alert" multiple={true} placeholder="Select One" onIonChange={e => setToppings(e.detail.value)} value={toppings} > <IonSelectOption value="bacon">Bacon</IonSelectOption> <IonSelectOption value="olives">Black Olives</IonSelectOption> <IonSelectOption value="xcheese">Extra Cheese</IonSelectOption> <IonSelectOption value="peppers">Green Peppers</IonSelectOption> <IonSelectOption value="mushrooms">Mushrooms</IonSelectOption> <IonSelectOption value="onions">Onions</IonSelectOption> <IonSelectOption value="pepperoni">Pepperoni</IonSelectOption> <IonSelectOption value="pineapple">Pineapple</IonSelectOption> <IonSelectOption value="sausage">Sausage</IonSelectOption> <IonSelectOption value="Spinach">Spinach</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Popover</IonLabel> <IonSelect interfaceOptions={customPopoverOptions} interface="popover" placeholder="Select One" onIonChange={e => setHairColor(e.detail.value)} value={hairColor}> <IonSelectOption value="brown">Brown</IonSelectOption> <IonSelectOption value="blonde">Blonde</IonSelectOption> <IonSelectOption value="black">Black</IonSelectOption> <IonSelectOption value="red">Red</IonSelectOption> </IonSelect> </IonItem> <IonItem> <IonLabel>Action Sheet</IonLabel> <IonSelect interfaceOptions={customActionSheetOptions} interface="action-sheet" placeholder="Select One" onIonChange={e => setColor(e.detail.value)} value={color} > <IonSelectOption value="red">Red</IonSelectOption> <IonSelectOption value="purple">Purple</IonSelectOption> <IonSelectOption value="yellow">Yellow</IonSelectOption> <IonSelectOption value="orange">Orange</IonSelectOption> <IonSelectOption value="green">Green</IonSelectOption> </IonSelect> </IonItem> <IonItemDivider>Your Selections</IonItemDivider> <IonItem>Toppings: {toppings.length ? toppings.reduce((curr, prev) => prev + ', ' + curr, '') : '(none selected)'}</IonItem> <IonItem>Hair Color: {hairColor}</IonItem> <IonItem>Color: {color ?? '(none selected)'}</IonItem> </IonList> </IonContent> </IonPage> ); }; ``` ### Stencil ### Single Selection ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { render() { return [ <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" okText="Okay" cancelText="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Multiple Selection ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { render() { return [ <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple={true} cancelText="Nah" okText="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple={true} value={['bird', 'dog']}> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Objects as Values ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { private users: any[] = [ { id: 1, first: 'Alice', last: 'Smith', }, { id: 2, first: 'Bob', last: 'Davis', }, { id: 3, first: 'Charlie', last: 'Rosenburg', } ]; compareWith = (o1, o2) => { return o1 && o2 ? o1.id === o2.id : o1 === o2; }; render() { return [ <ion-list> <ion-list-header> <ion-label> Objects as Values (compareWith) </ion-label> </ion-list-header> <ion-item> <ion-label>Users</ion-label> <ion-select compareWith={this.compareWith}> {this.users.map(user => <ion-select-option value={user}> {user.first + ' ' + user.last} </ion-select-option> )} </ion-select> </ion-item> </ion-list> ]; } } ``` ### Interface Options ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'select-example', styleUrl: 'select-example.css' }) export class SelectExample { private customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; private customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; private customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; render() { return [ <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select interfaceOptions={this.customAlertOptions} interface="alert" multiple={true} placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select interfaceOptions={this.customPopoverOptions} interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select interfaceOptions={this.customActionSheetOptions} interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> ]; } } ``` ### Vue ### Single Selection ```html <template> <ion-list> <ion-list-header> <ion-label> Single Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Gender</ion-label> <ion-select placeholder="Select One"> <ion-select-option value="f">Female</ion-select-option> <ion-select-option value="m">Male</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Hair Color</ion-label> <ion-select value="brown" ok-text="Okay" cancel-text="Dismiss"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } }); </script> ``` ### Multiple Selection ```html <template> <ion-list> <ion-list-header> <ion-label> Multiple Selection </ion-label> </ion-list-header> <ion-item> <ion-label>Toppings</ion-label> <ion-select multiple="true" cancel-text="Nah" ok-text="Okay!"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Pets</ion-label> <ion-select multiple="true" :value=['bird', 'dog']> <ion-select-option value="bird">Bird</ion-select-option> <ion-select-option value="cat">Cat</ion-select-option> <ion-select-option value="dog">Dog</ion-select-option> <ion-select-option value="honeybadger">Honey Badger</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } }); </script> ``` ### Interface Options ```html <template> <ion-list> <ion-list-header> <ion-label> Interface Options </ion-label> </ion-list-header> <ion-item> <ion-label>Alert</ion-label> <ion-select :interface-options="customAlertOptions" interface="alert" multiple="true" placeholder="Select One"> <ion-select-option value="bacon">Bacon</ion-select-option> <ion-select-option value="olives">Black Olives</ion-select-option> <ion-select-option value="xcheese">Extra Cheese</ion-select-option> <ion-select-option value="peppers">Green Peppers</ion-select-option> <ion-select-option value="mushrooms">Mushrooms</ion-select-option> <ion-select-option value="onions">Onions</ion-select-option> <ion-select-option value="pepperoni">Pepperoni</ion-select-option> <ion-select-option value="pineapple">Pineapple</ion-select-option> <ion-select-option value="sausage">Sausage</ion-select-option> <ion-select-option value="Spinach">Spinach</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Popover</ion-label> <ion-select :interface-options="customPopoverOptions" interface="popover" placeholder="Select One"> <ion-select-option value="brown">Brown</ion-select-option> <ion-select-option value="blonde">Blonde</ion-select-option> <ion-select-option value="black">Black</ion-select-option> <ion-select-option value="red">Red</ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>Action Sheet</ion-label> <ion-select :interface-options="customActionSheetOptions" interface="action-sheet" placeholder="Select One"> <ion-select-option value="red">Red</ion-select-option> <ion-select-option value="purple">Purple</ion-select-option> <ion-select-option value="yellow">Yellow</ion-select-option> <ion-select-option value="orange">Orange</ion-select-option> <ion-select-option value="green">Green</ion-select-option> </ion-select> </ion-item> </ion-list> </template> <script> import { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonItem, IonLabel, IonList, IonListHeader, IonSelect, IonSelectOption }, setup() { const customAlertOptions: any = { header: 'Pizza Toppings', subHeader: 'Select your toppings', message: '$1.00 per topping', translucent: true }; const customPopoverOptions: any = { header: 'Hair Color', subHeader: 'Select your hair color', message: 'Only select your dominant hair color' }; const customActionSheetOptions: any = { header: 'Colors', subHeader: 'Select your favorite color' }; return { customAlertOptions, customPopoverOptions, customActionSheetOptions } } }); </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ------------------ | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------- | | `cancelText` | `cancel-text` | The text to display on the cancel button. | `string` | `'Cancel'` | | `compareWith` | `compare-with` | A property name or function used to compare object values | `((currentValue: any, compareValue: any) => boolean) \| null \| string \| undefined` | `undefined` | | `disabled` | `disabled` | If `true`, the user cannot interact with the select. | `boolean` | `false` | | `interface` | `interface` | The interface the select should use: `action-sheet`, `popover` or `alert`. | `"action-sheet" \| "alert" \| "popover"` | `'alert'` | | `interfaceOptions` | `interface-options` | Any additional options that the `alert`, `action-sheet` or `popover` interface can take. See the [ion-alert docs](../alert), the [ion-action-sheet docs](../action-sheet) and the [ion-popover docs](../popover) for the create options for each interface. Note: `interfaceOptions` will not override `inputs` or `buttons` with the `alert` interface. | `any` | `{}` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `multiple` | `multiple` | If `true`, the select can accept multiple values. | `boolean` | `false` | | `name` | `name` | The name of the control, which is submitted with the form data. | `string` | `this.inputId` | | `okText` | `ok-text` | The text to display on the ok button. | `string` | `'OK'` | | `placeholder` | `placeholder` | The text to display when the select is empty. | `string \| undefined` | `undefined` | | `selectedText` | `selected-text` | The text to display instead of the selected option's value. | `null \| string \| undefined` | `undefined` | | `value` | `value` | the value of the select. | `any` | `undefined` | ## Events | Event | Description | Type | | ----------- | ---------------------------------------- | ------------------------------------------- | | `ionBlur` | Emitted when the select loses focus. | `CustomEvent<void>` | | `ionCancel` | Emitted when the selection is cancelled. | `CustomEvent<void>` | | `ionChange` | Emitted when the value has changed. | `CustomEvent<SelectChangeEventDetail<any>>` | | `ionFocus` | Emitted when the select has focus. | `CustomEvent<void>` | ## Methods ### `open(event?: UIEvent | undefined) => Promise<any>` Open the select overlay. The overlay is either an alert, action sheet, or popover, depending on the `interface` property on the `ion-select`. #### Returns Type: `Promise<any>` ## Shadow Parts | Part | Description | | --------------- | -------------------------------------------------------- | | `"icon"` | The select icon container. | | `"placeholder"` | The text displayed in the select when there is no value. | | `"text"` | The displayed value of the select. | ## CSS Custom Properties | Name | Description | | ----------------------- | --------------------------------------------------------------------------------------------------------- | | `--padding-bottom` | Bottom padding of the select | | `--padding-end` | Right padding if direction is left-to-right, and left padding if direction is right-to-left of the select | | `--padding-start` | Left padding if direction is left-to-right, and right padding if direction is right-to-left of the select | | `--padding-top` | Top padding of the select | | `--placeholder-color` | Color of the select placeholder text | | `--placeholder-opacity` | Opacity of the select placeholder text | ## Dependencies ### Depends on - ion-select-popover ### Graph ```mermaid graph TD; ion-select --> ion-select-popover ion-select-popover --> ion-item ion-select-popover --> ion-checkbox ion-select-popover --> ion-label ion-select-popover --> ion-radio-group ion-select-popover --> ion-radio ion-select-popover --> ion-list ion-select-popover --> ion-list-header ion-item --> ion-icon ion-item --> ion-ripple-effect ion-item --> ion-note style ion-select fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/select/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.20563340187072754, 0.0016114950412884355, 0.0001639045076444745, 0.00017306837253272533, 0.016943316906690598 ]
{ "id": 6, "code_window": [ "\n", "### Depends on\n", "\n", "- ion-select-popover\n", "\n", "### Graph\n", "```mermaid\n", "graph TD;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [ion-popover](../popover)\n", "- [ion-action-sheet](../action-sheet)\n", "- [ion-alert](../alert)\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1000 }
import { newE2EPage } from '@stencil/core/testing'; import { generateE2EUrl } from '@utils/test'; export const testToast = async ( type: string, selector: string, rtl = false ) => { try { const pageUrl = generateE2EUrl('toast', type, rtl); const page = await newE2EPage({ url: pageUrl }); const screenshotCompares = []; const button = await page.find(selector); await button.waitForVisible(); await button.click(); await page.waitForTimeout(250); let toast = await page.find('ion-toast'); await toast.waitForVisible(); expect(toast).not.toBe(null); await toast.waitForVisible(); screenshotCompares.push(await page.compareScreenshot()); await toast.callMethod('dismiss'); await toast.waitForNotVisible(); screenshotCompares.push(await page.compareScreenshot('dismiss')); toast = await page.find('ion-toast'); expect(toast).toBe(null); for (const screenshotCompare of screenshotCompares) { expect(screenshotCompare).toMatchScreenshot(); } } catch (err) { throw err; } };
core/src/components/toast/test/test.utils.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00020341435447335243, 0.0001781703031156212, 0.00016712189244572073, 0.00017315239529125392, 0.000013033597497269511 ]
{ "id": 6, "code_window": [ "\n", "### Depends on\n", "\n", "- ion-select-popover\n", "\n", "### Graph\n", "```mermaid\n", "graph TD;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [ion-popover](../popover)\n", "- [ion-action-sheet](../action-sheet)\n", "- [ion-alert](../alert)\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1000 }
```html <ion-content></ion-content> <!-- Footer without a border --> <ion-footer class="ion-no-border"> <ion-toolbar> <ion-title>Footer - No Border</ion-title> </ion-toolbar> </ion-footer> <ion-footer> <ion-toolbar> <ion-title>Footer</ion-title> </ion-toolbar> </ion-footer> <!-- Fade Footer --> <ion-footer collapse="fade"> <ion-toolbar> <ion-title>Footer</ion-title> </ion-toolbar> </ion-footer> ```
core/src/components/footer/usage/angular.md
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0002519017143640667, 0.00019761147268582135, 0.00016853315173648298, 0.0001723995228530839, 0.000038421439967351034 ]
{ "id": 6, "code_window": [ "\n", "### Depends on\n", "\n", "- ion-select-popover\n", "\n", "### Graph\n", "```mermaid\n", "graph TD;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "- [ion-popover](../popover)\n", "- [ion-action-sheet](../action-sheet)\n", "- [ion-alert](../alert)\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1000 }
/* eslint-disable */ /* tslint:disable */ /** * This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; export namespace Components { } declare global { interface HTMLElementTagNameMap { } } declare namespace LocalJSX { interface IntrinsicElements { } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { } } }
packages/vue/src/components.d.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0003003135498147458, 0.00021646353707183152, 0.00016967780538834631, 0.00017939928511623293, 0.000059423589846119285 ]
{ "id": 7, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-select --> ion-select-popover\n", " ion-select-popover --> ion-item\n", " ion-select-popover --> ion-checkbox\n", " ion-select-popover --> ion-label\n", " ion-select-popover --> ion-radio-group\n", " ion-select-popover --> ion-radio\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n", " ion-select --> ion-action-sheet\n", " ion-select --> ion-alert\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1005 }
# ion-popover A Popover is a dialog that appears on top of the current page. It can be used for anything, but generally it is used for overflow actions that don't fit in the navigation bar. There are two ways to use `ion-popover`: inline or via the `popoverController`. Each method comes with different considerations, so be sure to use the approach that best fits your use case. ## Inline Popovers `ion-popover` can be used by writing the component directly in your template. This reduces the number of handlers you need to wire up in order to present the popover. See [Usage](#usage) for an example of how to write a popover inline. When using `ion-popover` with Angular, React, or Vue, the component you pass in will be destroyed when the popover is dismissed. As this functionality is provided by the JavaScript framework, using `ion-popover` without a JavaScript framework will not destroy the component you passed in. If this is a needed functionality, we recommend using the `popoverController` instead. ### Angular Since the component you passed in needs to be created when the popover is presented and destroyed when the popover is dismissed, we are unable to project the content using `<ng-content>` internally. Instead, we use `<ng-container>` which expects an `<ng-template>` to be passed in. As a result, when passing in your component you will need to wrap it in an `<ng-template>`: ```html <ion-popover [isOpen]="isPopoverOpen"> <ng-template> <app-popover-content></app-popover-content> </ng-template> </ion-popover> ``` ### When to use Using a popover inline is useful when you do not want to explicitly wire up click events to open the popover. For example, you can use the `trigger` property to designate a button that should present the popover when clicked. You can also use the `trigger-action` property to customize whether the popover should be presented when the trigger is left clicked, right clicked, or hovered over. If you need fine grained control over when the popover is presented and dismissed, we recommend you use the `popoverController`. ## Controller Popovers `ion-popover` can also be presented programmatically by using the `popoverController` imported from Ionic Framework. This allows you to have complete control over when a popover is presented above and beyond the customization that inline popovers give you. See [Usage](#usage) for an example of how to use the `popoverController`. ### When to use We typically recommend that you write your popovers inline as it streamlines the amount of code in your application. You should only use the `popoverController` for complex use cases where writing a popover inline is impractical. When using a controller, your popover is not created ahead of time, so properties such as `trigger` and `trigger-action` are not applicable here. In addition, nested popovers are not compatible with the controller approach because the popover is automatically added to the root of your application when the `create` method is called. ## Styling Popovers are presented at the root of your application so they overlay your entire app. This behavior applies to both inline popovers and popovers presented from a controller. As a result, custom popover styles can not be scoped to a particular component as they will not apply to the popover. Instead, styles must be applied globally. For most developers, placing the custom styles in `global.css` is sufficient. > If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information. ## Triggers A trigger for an `ion-popover` is the element that will open a popover when interacted with. The interaction behavior can be customized by setting the `trigger-action` property. Note that `trigger-action="context-menu"` will prevent your system's default context menu from opening. View the [Usage](#usage) section for an example of how to use triggers. > Triggers are not applicable when using the `popoverController` because the `ion-popover` is not created ahead of time. ## Positioning ### Reference When presenting a popover, Ionic Framework needs a reference point to present the popover relative to. With `reference="event"`, the popover will be presented relative to the x-y coordinates of the pointer event that was dispatched on your trigger element. With `reference="trigger"`, the popover will be presented relative to the bounding box of your trigger element. ### Side Regardless of what you choose for your reference point, you can position a popover to the `top`, `right`, `left`, or `bottom` of your reference point by using the `side` property. You can also use the `start` or `end` values if you would like the side to switch based on LTR or RTL modes. ### Alignment The `alignment` property allows you to line up an edge of your popover with a corresponding edge on your trigger element. The exact edge that is used depends on the value of the `side` property. ### Offsets If you need finer grained control over the positioning of your popover you can use the `--offset-x` and `--offset-y` CSS Variables. For example, `--offset-x: 10px` will move your popover content to the right by `10px`. ## Sizing When making dropdown menus, you may want to have the width of the popover match the width of the trigger element. Doing this without knowing the trigger width ahead of time is tricky. You can set the `size` property to `'cover'` and Ionic Framework will ensure that the width of the popover matches the width of your trigger element. If you are using the `popoverController`, you must provide an event via the `event` option and Ionic Framework will use `event.target` as the reference element. ## Nested Popovers When using `ion-popover` inline, you can nested popovers to create nested dropdown menus. When doing this, only the backdrop on the first popover will appear so that the screen does not get progressively darker as you open more popovers. See the [Usage](./#usage) section for an example on how to write a nested popover. You can use the `dismissOnSelect` property to automatically close the popover when the popover content has been clicked. This behavior does not apply when clicking a trigger element for another popover. > Nested popovers cannot be created when using the `popoverController` because the popover is automatically added to the root of your application when the `create` method is called. ## Interfaces Below you will find all of the options available to you when using the `popoverController`. These options should be supplied when calling `popoverController.create()`. ```typescript interface PopoverOptions { component: any; componentProps?: { [key: string]: any }; showBackdrop?: boolean; backdropDismiss?: boolean; translucent?: boolean; cssClass?: string | string[]; event?: Event; animated?: boolean; mode?: 'ios' | 'md'; keyboardClose?: boolean; id?: string; htmlAttributes?: PopoverAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; size?: PopoverSize; dismissOnSelect?: boolean; reference?: PositionReference; side?: PositionSide; alignment?: PositionAlign; arrow?: boolean; } ``` ### PopoverAttributes ```typescript interface PopoverAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} ``` ## Types Below you will find all of the custom types for `ion-popover`: ```typescript type PopoverSize = 'cover' | 'auto'; type TriggerAction = 'click' | 'hover' | 'context-menu'; type PositionReference = 'trigger' | 'event'; type PositionSide = 'top' | 'right' | 'bottom' | 'left' | 'start' | 'end'; type PositionAlign = 'start' | 'center' | 'end'; ``` ## Accessibility ### Keyboard Navigation `ion-popover` has basic keyboard support for navigating between focusable elements inside of the popover. The following table details what each key does: | Key | Function | | ------------------ | ------------------------------------------------------------ | | `Tab` | Moves focus to the next focusable element. | | `Shift` + `Tab` | Moves focus to the previous focusable element. | | `Esc` | Closes the popover. | | `Space` or `Enter` | Clicks the focusable element. | `ion-popover` has full arrow key support for navigating between `ion-item` elements with the `button` property. The most common use case for this is as a dropdown menu in a desktop-focused application. In addition to the basic keyboard support, the following table details arrow key support for dropdown menus: | Key | Function | | ------------------ | -------------------------------------------------------------- | | `ArrowUp` | Moves focus to the previous focusable element. | | `ArrowDown` | Moves focus to the next focusable element. | | `Home` | Moves focus to the first focusable element. | | `End` | Moves focus to the last focusable element. | | `ArrowLeft` | When used in a child popover, closes the popover and returns focus to the parent popover. | | `Space`, `Enter`, and `ArrowRight` | When focusing a trigger element, opens the associated popover. | <!-- Auto Generated Below --> ## Usage ### Angular ### Inline Popover ```html <!-- Default --> <ion-popover [isOpen]="true"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- No Arrow --> <ion-popover [isOpen]="true" [arrow]="false"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" [dismissOnSelect]="true"> <ng-template> <ion-content> <ion-list> <ion-item [button]="true" [detail]="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item [button]="true" [detail]="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item [button]="true" [detail]="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" [dismissOnSelect]="true" side="end"> <ng-template> <ion-content> <ion-item [button]="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ng-template> </ion-popover> </ion-list> </ion-content> </ng-template> </ion-popover> ``` ### Popover Controller ```typescript import { Component } from '@angular/core'; import { PopoverController } from '@ionic/angular'; import { PopoverComponent } from '../../component/popover/popover.component'; @Component({ selector: 'popover-example', templateUrl: 'popover-example.html', styleUrls: ['./popover-example.css'] }) export class PopoverExample { constructor(public popoverController: PopoverController) {} async presentPopover(ev: any) { const popover = await this.popoverController.create({ component: PopoverComponent, cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } } ``` ### Style Placement In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Popover can be presented from within a page, the `ion-popover` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config). ### Javascript ### Inline Popover ```html <!-- Default --> <ion-popover is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover is-open="true" arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismiss-on-select="true"> <ion-content> <ion-list> <ion-item button="true" detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item button="true" detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item button="true" detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismiss-on-select="true" side="end"> <ion-content> <ion-item button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> ``` ### Using JavaScript ```javascript class PopoverExamplePage extends HTMLElement { constructor() { super(); } connectedCallback() { this.innerHTML = ` <ion-content> <ion-list> <ion-list-header><ion-label>Ionic</ion-label></ion-list-header> <ion-item button><ion-label>Item 0</ion-label></ion-item> <ion-item button><ion-label>Item 1</ion-label></ion-item> <ion-item button><ion-label>Item 2</ion-label></ion-item> <ion-item button><ion-label>Item 3</ion-label></ion-item> </ion-list> </ion-content> `; } } customElements.define('popover-example-page', PopoverExamplePage); async function presentPopover(ev) { const popover = Object.assign(document.createElement('ion-popover'), { component: 'popover-example-page', cssClass: 'my-custom-class', event: ev, translucent: true }); document.body.appendChild(popover); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } ``` ### React ### Inline Popover ```tsx import React, { useState } from 'react'; import { IonPopover, IonContent, IonItem, IonLabel, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { return ( <> {/* Default */} <IonPopover isOpen={true}> <IonContent>Popover Content</IonContent> </IonPopover> {/* No Arrow */} <IonPopover isOpen={true} arrow={false}> <IonContent>Popover Content</IonContent> </IonPopover> {/* Use a trigger */} <IonButton id="trigger-button">Click to open popover</IonButton> <IonPopover trigger="trigger-button"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Hover over trigger to open */} <IonButton id="hover-button">Hover to open popover</IonButton> <IonPopover trigger="hover-button" triggerAction="hover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Show popover above trigger */} <IonButton id="side-button">Click to open popover</IonButton> <IonPopover trigger="side-button" side="top"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Align popover to end of trigger */} <IonButton id="alignment-button">Click to open popover</IonButton> <IonPopover trigger="alignment-button" side="top" alignment="end"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover the same size as the trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" size="cover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover show relative to click coordinates rather than trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" reference="event"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Nested Popover */} <IonButton id="nested-button">Click to open popover</IonButton> <IonPopover trigger="nested-button" dismissOnSelect={true}> <IonContent> <ion-list> <IonItem button={true} detail={false}> <IonLabel>Option 1</IonLabel> </IonItem> <IonItem button={true} detail={false}> <IonLabel>Option 2</IonLabel> </IonItem> <IonItem button={true} detail={true} id="nested-trigger"> <IonLabel>Option 3</IonLabel> </IonItem> <IonPopover trigger="nested-trigger" dismissOnSelect={true} side="end"> <IonContent> <IonItem button={true}> <IonLabel>Nested Option</IonLabel> </IonItem> </IonContent> </IonPopover> </ion-list> </IonContent> </IonPopover> </> ); }; ``` ### Inline Popover with State ```tsx import React, { useState } from 'react'; import { IonPopover, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { const [popoverState, setShowPopover] = useState({ showPopover: false, event: undefined }); return ( <> <IonPopover cssClass='my-custom-class' event={popoverState.event} isOpen={popoverState.showPopover} onDidDismiss={() => setShowPopover({ showPopover: false, event: undefined })} > <p>This is popover content</p> </IonPopover> <IonButton onClick={ (e: any) => { e.persist(); setShowPopover({ showPopover: true, event: e }) }} > Show Popover </IonButton> </> ); }; ``` ### useIonPopover Hook > `useIonPopover` requires being a descendant of `<IonApp>`. If you need to use a popover outside of an `<IonApp>`, consider using the component method instead. ```tsx import React from 'react'; import { IonButton, IonContent, IonItem, IonList, IonListHeader, IonPage, useIonPopover, } from '@ionic/react'; const PopoverList: React.FC<{ onHide: () => void; }> = ({ onHide }) => ( <IonList> <IonListHeader>Ionic</IonListHeader> <IonItem button>Learn Ionic</IonItem> <IonItem button>Documentation</IonItem> <IonItem button>Showcase</IonItem> <IonItem button>GitHub Repo</IonItem> <IonItem lines="none" detail={false} button onClick={onHide}> Close </IonItem> </IonList> ); const PopoverExample: React.FC = () => { const [present, dismiss] = useIonPopover(PopoverList, { onHide: () => dismiss() }); return ( <IonPage> <IonContent> <IonButton expand="block" onClick={(e) => present({ event: e.nativeEvent, }) } > Show Popover </IonButton> </IonContent> </IonPage> ); }; ``` ### Stencil ### Inline Popover ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { render() { return [ <ion-content> {/* Default */} <ion-popover isOpen={true}> <ion-content>Popover Content</ion-content> </ion-popover> {/* No Arrow */} <ion-popover isOpen={true} arrow={false}> <ion-content>Popover Content</ion-content> </ion-popover> {/* Use a trigger */} <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Hover over trigger to open */} <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Show popover above trigger */} <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Align popover to end of trigger */} <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover the same size as the trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover show relative to click coordinates rather than trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Nested Popover */} <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismissOnSelect={true}> <ion-content> <ion-list> <ion-item button={true} detail={false}> <ion-label>Option 1</ion-label> </ion-item> <ion-item button={true} detail={false}> <ion-label>Option 2</ion-label> </ion-item> <ion-item button={true} detail={true} id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismissOnSelect={true} side="end"> <ion-content> <ion-item button={true}> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Popover Controller ```tsx import { Component, h } from '@stencil/core'; import { popoverController } from '@ionic/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { async presentPopover(ev: any) { const popover = await popoverController.create({ component: 'page-popover', cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } render() { return [ <ion-content> <ion-button onClick={(ev) => this.presentPopover(ev)}>Present Popover</ion-button> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Vue ### Inline Popover ```html <template> <!-- Default --> <ion-popover :is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover :is-open="true" :arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" :dismiss-on-select="true"> <ion-content> <ion-list> <ion-item :button="true" :detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item :button="true" :detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item :button="true" :detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" :dismiss-on-select="true" side="end"> <ion-content> <ion-item :button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </template> <script> import { IonButton, IonContent, IonItem, IonLabel, IonPopover } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonButton, IonContent, IonItem, IonLabel, IonPopover } }); </script> ``` ### Inline Popover with State ```html <template> <ion-button @click="setOpen(true, $event)">Show Popover</ion-button> <ion-popover :is-open="isOpenRef" css-class="my-custom-class" :event="event" :translucent="true" @didDismiss="setOpen(false)" > <Popover></Popover> </ion-popover> </template> <script> import { IonButton, IonPopover } from '@ionic/vue'; import { defineComponent, ref } from 'vue'; import Popover from './popover.vue'; export default defineComponent({ components: { IonButton, IonPopover, Popover }, setup() { const isOpenRef = ref(false); const event = ref(); const setOpen = (state: boolean, ev?: Event) => { event.value = ev; isOpenRef.value = state; } return { isOpenRef, setOpen, event } } }); </script> ``` ### Popover Controller ```html <template> <ion-content class="ion-padding"> Popover Content </ion-content> </template> <script> import { IonContent } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Popover', components: { IonContent } }); </script> ``` ```html <template> <ion-page> <ion-content class="ion-padding"> <ion-button @click="openPopover">Open Popover</ion-button> </ion-content> </ion-page> </template> <script> import { IonButton, IonContent, IonPage, popoverController } from '@ionic/vue'; import Popover from './popover.vue'; export default { components: { IonButton, IonContent, IonPage }, methods: { async openPopover(ev: Event) { const popover = await popoverController .create({ component: Popover, cssClass: 'my-custom-class', event: ev, translucent: true }) await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); }, }, } </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------- | | `alignment` | `alignment` | Describes how to align the popover content with the `reference` point. Defaults to `'center'` for `ios` mode, and `'start'` for `md` mode. | `"center" \| "end" \| "start" \| undefined` | `undefined` | | `animated` | `animated` | If `true`, the popover will animate. | `boolean` | `true` | | `arrow` | `arrow` | If `true`, the popover will display an arrow that points at the `reference` when running in `ios` mode on mobile. Does not apply in `md` mode or on desktop. | `boolean` | `true` | | `backdropDismiss` | `backdrop-dismiss` | If `true`, the popover will be dismissed when the backdrop is clicked. | `boolean` | `true` | | `component` | `component` | The component to display inside of the popover. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just slot your component inside of `ion-popover`. | `Function \| HTMLElement \| null \| string \| undefined` | `undefined` | | `componentProps` | -- | The data to pass to the popover component. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just set the props directly on your component. | `undefined \| { [key: string]: any; }` | `undefined` | | `dismissOnSelect` | `dismiss-on-select` | If `true`, the popover will be automatically dismissed when the content has been clicked. | `boolean` | `false` | | `enterAnimation` | -- | Animation to use when the popover is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `event` | `event` | The event to pass to the popover animation. | `any` | `undefined` | | `htmlAttributes` | -- | Additional attributes to pass to the popover. | `PopoverAttributes \| undefined` | `undefined` | | `isOpen` | `is-open` | If `true`, the popover will open. If `false`, the popover will close. Use this if you need finer grained control over presentation, otherwise just use the popoverController or the `trigger` property. Note: `isOpen` will not automatically be set back to `false` when the popover dismisses. You will need to do that in your code. | `boolean` | `false` | | `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` | | `leaveAnimation` | -- | Animation to use when the popover is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `reference` | `reference` | Describes what to position the popover relative to. If `'trigger'`, the popover will be positioned relative to the trigger button. If passing in an event, this is determined via event.target. If `'event'`, the popover will be positioned relative to the x/y coordinates of the trigger action. If passing in an event, this is determined via event.clientX and event.clientY. | `"event" \| "trigger"` | `'trigger'` | | `showBackdrop` | `show-backdrop` | If `true`, a backdrop will be displayed behind the popover. | `boolean` | `true` | | `side` | `side` | Describes which side of the `reference` point to position the popover on. The `'start'` and `'end'` values are RTL-aware, and the `'left'` and `'right'` values are not. | `"bottom" \| "end" \| "left" \| "right" \| "start" \| "top"` | `'bottom'` | | `size` | `size` | Describes how to calculate the popover width. If `'cover'`, the popover width will match the width of the trigger. If `'auto'`, the popover width will be determined by the content in the popover. | `"auto" \| "cover"` | `'auto'` | | `translucent` | `translucent` | If `true`, the popover will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` | | `trigger` | `trigger` | An ID corresponding to the trigger element that causes the popover to open. Use the `trigger-action` property to customize the interaction that results in the popover opening. | `string \| undefined` | `undefined` | | `triggerAction` | `trigger-action` | Describes what kind of interaction with the trigger that should cause the popover to open. Does not apply when the `trigger` property is `undefined`. If `'click'`, the popover will be presented when the trigger is left clicked. If `'hover'`, the popover will be presented when a pointer hovers over the trigger. If `'context-menu'`, the popover will be presented when the trigger is right clicked on desktop and long pressed on mobile. This will also prevent your device's normal context menu from appearing. | `"click" \| "context-menu" \| "hover"` | `'click'` | ## Events | Event | Description | Type | | ----------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | | `didDismiss` | Emitted after the popover has dismissed. Shorthand for ionPopoverDidDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `didPresent` | Emitted after the popover has presented. Shorthand for ionPopoverWillDismiss. | `CustomEvent<void>` | | `ionPopoverDidDismiss` | Emitted after the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverDidPresent` | Emitted after the popover has presented. | `CustomEvent<void>` | | `ionPopoverWillDismiss` | Emitted before the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverWillPresent` | Emitted before the popover has presented. | `CustomEvent<void>` | | `willDismiss` | Emitted before the popover has dismissed. Shorthand for ionPopoverWillDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `willPresent` | Emitted before the popover has presented. Shorthand for ionPopoverWillPresent. | `CustomEvent<void>` | ## Methods ### `dismiss(data?: any, role?: string | undefined, dismissParentPopover?: boolean) => Promise<boolean>` Dismiss the popover overlay after it has been presented. #### Returns Type: `Promise<boolean>` ### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover did dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover will dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `present(event?: MouseEvent | TouchEvent | PointerEvent | CustomEvent<any> | undefined) => Promise<void>` Present the popover overlay after it has been created. Developers can pass a mouse, touch, or pointer event to position the popover relative to where that event was dispatched. #### Returns Type: `Promise<void>` ## Slots | Slot | Description | | ---- | ----------------------------------------------------------- | | | Content is placed inside of the `.popover-content` element. | ## Shadow Parts | Part | Description | | ------------ | --------------------------------------------------------------------------- | | `"arrow"` | The arrow that points to the reference element. Only applies on `ios` mode. | | `"backdrop"` | The `ion-backdrop` element. | | `"content"` | The wrapper element for the default slot. | ## CSS Custom Properties | Name | Description | | -------------------- | ----------------------------------------------- | | `--backdrop-opacity` | Opacity of the backdrop | | `--background` | Background of the popover | | `--box-shadow` | Box shadow of the popover | | `--height` | Height of the popover | | `--max-height` | Maximum height of the popover | | `--max-width` | Maximum width of the popover | | `--min-height` | Minimum height of the popover | | `--min-width` | Minimum width of the popover | | `--offset-x` | The amount to move the popover by on the x-axis | | `--offset-y` | The amount to move the popover by on the y-axis | | `--width` | Width of the popover | ## Dependencies ### Used by - [ion-datetime](../datetime) ### Depends on - [ion-backdrop](../backdrop) ### Graph ```mermaid graph TD; ion-popover --> ion-backdrop ion-datetime --> ion-popover style ion-popover fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/popover/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.9544202089309692, 0.009119385853409767, 0.0001603970886208117, 0.00018535659182816744, 0.0905490294098854 ]
{ "id": 7, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-select --> ion-select-popover\n", " ion-select-popover --> ion-item\n", " ion-select-popover --> ion-checkbox\n", " ion-select-popover --> ion-label\n", " ion-select-popover --> ion-radio-group\n", " ion-select-popover --> ion-radio\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n", " ion-select --> ion-action-sheet\n", " ion-select --> ion-alert\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1005 }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Modal - Basic</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script> <style> :root { --ion-safe-area-top: 20px; --ion-safe-area-bottom: 20px; --ion-safe-area-right: 20px; --ion-safe-area-left: 20px; } </style> </head> <body> <ion-app> <div class="ion-page"> <ion-header> <ion-toolbar> <ion-title>Modal - Basic</ion-title> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <p> <ion-button id="basic-modal" onclick="presentModal()">Present modal</ion-button> </p> <p> <ion-button id="presentModal" class="e2ePresentModal" onclick="presentCloseModal()">Present and close modal</ion-button> </p> <p> <ion-button id="presentModal" class="e2ePresentModal" onclick="presentCloseModal2()">Present and close modal (crash)</ion-button> </p> </ion-content> </div> </ion-app> <script> window.addEventListener("ionModalDidDismiss", function (e) { console.log('DidDismiss', e) }) window.addEventListener("ionModalWillDismiss", function (e) { console.log('WillDismiss', e) }) function createModal() { // create component to open const element = document.createElement('div'); element.innerHTML = ` <ion-header> <ion-toolbar> <ion-title>Super Modal</ion-title> </ion-toolbar> </ion-header> <ion-content> <h1>Content of doom</h1> <div>Here's some more content</div> <ion-button class="dismiss">Dismiss Modal</ion-button> </ion-content> `; // present the modal const modalElement = Object.assign(document.createElement('ion-modal'), { component: element, htmlAttributes: { 'data-testid': 'basic-modal' } }); // listen for close event const button = element.querySelector('ion-button'); button.addEventListener('click', () => { modalElement.dismiss(); }); document.body.appendChild(modalElement); return modalElement; } async function presentModal() { const presentingEl = document.querySelectorAll('.ion-page')[1]; const modal = createModal(); await modal.present(presentingEl); } async function presentCloseModal() { const modal = createModal(); await modal.present(); await modal.dismiss(); } async function presentCloseModal2() { const modal = createModal(); modal.present(); setTimeout(() => { modal.dismiss(); }, 20); } </script> </body> </html>
core/src/components/modal/test/basic/index.html
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00021311397722456604, 0.00017412051965948194, 0.00016658382082823664, 0.00016902462812140584, 0.000012908554708701558 ]
{ "id": 7, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-select --> ion-select-popover\n", " ion-select-popover --> ion-item\n", " ion-select-popover --> ion-checkbox\n", " ion-select-popover --> ion-label\n", " ion-select-popover --> ion-radio-group\n", " ion-select-popover --> ion-radio\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n", " ion-select --> ion-action-sheet\n", " ion-select --> ion-alert\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1005 }
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title>Segment - RTL</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link href="../../../../../css/ionic.bundle.css" rel="stylesheet"> <link href="../../../../../scripts/testing/styles.css" rel="stylesheet"> <script src="../../../../../scripts/testing/scripts.js"></script> <script nomodule src="../../../../../dist/ionic/ionic.js"></script> <script type="module" src="../../../../../dist/ionic/ionic.esm.js"></script> </head> <body> <ion-app> <ion-header> <ion-toolbar> <ion-title>Segment - RTL</ion-title> </ion-toolbar> <ion-content> <div class="ion-padding"> <ion-segment dir="rtl"> <ion-segment-button> <ion-label>Seg 1</ion-label> </ion-segment-button> <ion-segment-button> <ion-label>Seg 2</ion-label> </ion-segment-button> <ion-segment-button> <ion-label>Seg 3</ion-label> </ion-segment-button> </ion-segment> </ion-content> </ion-app> </body> </html>
core/src/components/segment/test/rtl/index.html
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017234118422493339, 0.00016850398969836533, 0.00016566224803682417, 0.00016696118109393865, 0.0000025534118321957067 ]
{ "id": 7, "code_window": [ "```mermaid\n", "graph TD;\n", " ion-select --> ion-select-popover\n", " ion-select-popover --> ion-item\n", " ion-select-popover --> ion-checkbox\n", " ion-select-popover --> ion-label\n", " ion-select-popover --> ion-radio-group\n", " ion-select-popover --> ion-radio\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-select --> ion-popover\n", " ion-select --> ion-action-sheet\n", " ion-select --> ion-alert\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1005 }
/// <reference types="cypress" /> // *********************************************************** // This example plugins/index.js can be used to load plugins // // You can change the location of this file or turn off loading // the plugins file with the 'pluginsFile' configuration option. // // You can read more here: // https://on.cypress.io/plugins-guide // *********************************************************** // This function is called when a project is opened or re-opened (e.g. due to // the project's config changing) /** * @type {Cypress.PluginConfig} */ module.exports = (on, config) => { // `on` is used to hook into various events Cypress emits // `config` is the resolved Cypress config };
packages/react-router/test-app/cypress/plugins/index.js
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017731466505210847, 0.00017367566761095077, 0.00017085175204556435, 0.00017286058573517948, 0.000002700688810364227 ]
{ "id": 8, "code_window": [ " ion-item --> ion-icon\n", " ion-item --> ion-ripple-effect\n", " ion-item --> ion-note\n", " style ion-select fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-popover --> ion-backdrop\n", " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1015 }
# ion-popover A Popover is a dialog that appears on top of the current page. It can be used for anything, but generally it is used for overflow actions that don't fit in the navigation bar. There are two ways to use `ion-popover`: inline or via the `popoverController`. Each method comes with different considerations, so be sure to use the approach that best fits your use case. ## Inline Popovers `ion-popover` can be used by writing the component directly in your template. This reduces the number of handlers you need to wire up in order to present the popover. See [Usage](#usage) for an example of how to write a popover inline. When using `ion-popover` with Angular, React, or Vue, the component you pass in will be destroyed when the popover is dismissed. As this functionality is provided by the JavaScript framework, using `ion-popover` without a JavaScript framework will not destroy the component you passed in. If this is a needed functionality, we recommend using the `popoverController` instead. ### Angular Since the component you passed in needs to be created when the popover is presented and destroyed when the popover is dismissed, we are unable to project the content using `<ng-content>` internally. Instead, we use `<ng-container>` which expects an `<ng-template>` to be passed in. As a result, when passing in your component you will need to wrap it in an `<ng-template>`: ```html <ion-popover [isOpen]="isPopoverOpen"> <ng-template> <app-popover-content></app-popover-content> </ng-template> </ion-popover> ``` ### When to use Using a popover inline is useful when you do not want to explicitly wire up click events to open the popover. For example, you can use the `trigger` property to designate a button that should present the popover when clicked. You can also use the `trigger-action` property to customize whether the popover should be presented when the trigger is left clicked, right clicked, or hovered over. If you need fine grained control over when the popover is presented and dismissed, we recommend you use the `popoverController`. ## Controller Popovers `ion-popover` can also be presented programmatically by using the `popoverController` imported from Ionic Framework. This allows you to have complete control over when a popover is presented above and beyond the customization that inline popovers give you. See [Usage](#usage) for an example of how to use the `popoverController`. ### When to use We typically recommend that you write your popovers inline as it streamlines the amount of code in your application. You should only use the `popoverController` for complex use cases where writing a popover inline is impractical. When using a controller, your popover is not created ahead of time, so properties such as `trigger` and `trigger-action` are not applicable here. In addition, nested popovers are not compatible with the controller approach because the popover is automatically added to the root of your application when the `create` method is called. ## Styling Popovers are presented at the root of your application so they overlay your entire app. This behavior applies to both inline popovers and popovers presented from a controller. As a result, custom popover styles can not be scoped to a particular component as they will not apply to the popover. Instead, styles must be applied globally. For most developers, placing the custom styles in `global.css` is sufficient. > If you are building an Ionic Angular app, the styles need to be added to a global stylesheet file. Read [Style Placement](#style-placement) in the Angular section below for more information. ## Triggers A trigger for an `ion-popover` is the element that will open a popover when interacted with. The interaction behavior can be customized by setting the `trigger-action` property. Note that `trigger-action="context-menu"` will prevent your system's default context menu from opening. View the [Usage](#usage) section for an example of how to use triggers. > Triggers are not applicable when using the `popoverController` because the `ion-popover` is not created ahead of time. ## Positioning ### Reference When presenting a popover, Ionic Framework needs a reference point to present the popover relative to. With `reference="event"`, the popover will be presented relative to the x-y coordinates of the pointer event that was dispatched on your trigger element. With `reference="trigger"`, the popover will be presented relative to the bounding box of your trigger element. ### Side Regardless of what you choose for your reference point, you can position a popover to the `top`, `right`, `left`, or `bottom` of your reference point by using the `side` property. You can also use the `start` or `end` values if you would like the side to switch based on LTR or RTL modes. ### Alignment The `alignment` property allows you to line up an edge of your popover with a corresponding edge on your trigger element. The exact edge that is used depends on the value of the `side` property. ### Offsets If you need finer grained control over the positioning of your popover you can use the `--offset-x` and `--offset-y` CSS Variables. For example, `--offset-x: 10px` will move your popover content to the right by `10px`. ## Sizing When making dropdown menus, you may want to have the width of the popover match the width of the trigger element. Doing this without knowing the trigger width ahead of time is tricky. You can set the `size` property to `'cover'` and Ionic Framework will ensure that the width of the popover matches the width of your trigger element. If you are using the `popoverController`, you must provide an event via the `event` option and Ionic Framework will use `event.target` as the reference element. ## Nested Popovers When using `ion-popover` inline, you can nested popovers to create nested dropdown menus. When doing this, only the backdrop on the first popover will appear so that the screen does not get progressively darker as you open more popovers. See the [Usage](./#usage) section for an example on how to write a nested popover. You can use the `dismissOnSelect` property to automatically close the popover when the popover content has been clicked. This behavior does not apply when clicking a trigger element for another popover. > Nested popovers cannot be created when using the `popoverController` because the popover is automatically added to the root of your application when the `create` method is called. ## Interfaces Below you will find all of the options available to you when using the `popoverController`. These options should be supplied when calling `popoverController.create()`. ```typescript interface PopoverOptions { component: any; componentProps?: { [key: string]: any }; showBackdrop?: boolean; backdropDismiss?: boolean; translucent?: boolean; cssClass?: string | string[]; event?: Event; animated?: boolean; mode?: 'ios' | 'md'; keyboardClose?: boolean; id?: string; htmlAttributes?: PopoverAttributes; enterAnimation?: AnimationBuilder; leaveAnimation?: AnimationBuilder; size?: PopoverSize; dismissOnSelect?: boolean; reference?: PositionReference; side?: PositionSide; alignment?: PositionAlign; arrow?: boolean; } ``` ### PopoverAttributes ```typescript interface PopoverAttributes extends JSXBase.HTMLAttributes<HTMLElement> {} ``` ## Types Below you will find all of the custom types for `ion-popover`: ```typescript type PopoverSize = 'cover' | 'auto'; type TriggerAction = 'click' | 'hover' | 'context-menu'; type PositionReference = 'trigger' | 'event'; type PositionSide = 'top' | 'right' | 'bottom' | 'left' | 'start' | 'end'; type PositionAlign = 'start' | 'center' | 'end'; ``` ## Accessibility ### Keyboard Navigation `ion-popover` has basic keyboard support for navigating between focusable elements inside of the popover. The following table details what each key does: | Key | Function | | ------------------ | ------------------------------------------------------------ | | `Tab` | Moves focus to the next focusable element. | | `Shift` + `Tab` | Moves focus to the previous focusable element. | | `Esc` | Closes the popover. | | `Space` or `Enter` | Clicks the focusable element. | `ion-popover` has full arrow key support for navigating between `ion-item` elements with the `button` property. The most common use case for this is as a dropdown menu in a desktop-focused application. In addition to the basic keyboard support, the following table details arrow key support for dropdown menus: | Key | Function | | ------------------ | -------------------------------------------------------------- | | `ArrowUp` | Moves focus to the previous focusable element. | | `ArrowDown` | Moves focus to the next focusable element. | | `Home` | Moves focus to the first focusable element. | | `End` | Moves focus to the last focusable element. | | `ArrowLeft` | When used in a child popover, closes the popover and returns focus to the parent popover. | | `Space`, `Enter`, and `ArrowRight` | When focusing a trigger element, opens the associated popover. | <!-- Auto Generated Below --> ## Usage ### Angular ### Inline Popover ```html <!-- Default --> <ion-popover [isOpen]="true"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- No Arrow --> <ion-popover [isOpen]="true" [arrow]="false"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ng-template> <ion-content>Popover Content</ion-content> </ng-template> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" [dismissOnSelect]="true"> <ng-template> <ion-content> <ion-list> <ion-item [button]="true" [detail]="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item [button]="true" [detail]="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item [button]="true" [detail]="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" [dismissOnSelect]="true" side="end"> <ng-template> <ion-content> <ion-item [button]="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ng-template> </ion-popover> </ion-list> </ion-content> </ng-template> </ion-popover> ``` ### Popover Controller ```typescript import { Component } from '@angular/core'; import { PopoverController } from '@ionic/angular'; import { PopoverComponent } from '../../component/popover/popover.component'; @Component({ selector: 'popover-example', templateUrl: 'popover-example.html', styleUrls: ['./popover-example.css'] }) export class PopoverExample { constructor(public popoverController: PopoverController) {} async presentPopover(ev: any) { const popover = await this.popoverController.create({ component: PopoverComponent, cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } } ``` ### Style Placement In Angular, the CSS of a specific page is scoped only to elements of that page. Even though the Popover can be presented from within a page, the `ion-popover` element is appended outside of the current page. This means that any custom styles need to go in a global stylesheet file. In an Ionic Angular starter this can be the `src/global.scss` file or you can register a new global style file by [adding to the `styles` build option in `angular.json`](https://angular.io/guide/workspace-config#style-script-config). ### Javascript ### Inline Popover ```html <!-- Default --> <ion-popover is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover is-open="true" arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismiss-on-select="true"> <ion-content> <ion-list> <ion-item button="true" detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item button="true" detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item button="true" detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismiss-on-select="true" side="end"> <ion-content> <ion-item button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> ``` ### Using JavaScript ```javascript class PopoverExamplePage extends HTMLElement { constructor() { super(); } connectedCallback() { this.innerHTML = ` <ion-content> <ion-list> <ion-list-header><ion-label>Ionic</ion-label></ion-list-header> <ion-item button><ion-label>Item 0</ion-label></ion-item> <ion-item button><ion-label>Item 1</ion-label></ion-item> <ion-item button><ion-label>Item 2</ion-label></ion-item> <ion-item button><ion-label>Item 3</ion-label></ion-item> </ion-list> </ion-content> `; } } customElements.define('popover-example-page', PopoverExamplePage); async function presentPopover(ev) { const popover = Object.assign(document.createElement('ion-popover'), { component: 'popover-example-page', cssClass: 'my-custom-class', event: ev, translucent: true }); document.body.appendChild(popover); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } ``` ### React ### Inline Popover ```tsx import React, { useState } from 'react'; import { IonPopover, IonContent, IonItem, IonLabel, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { return ( <> {/* Default */} <IonPopover isOpen={true}> <IonContent>Popover Content</IonContent> </IonPopover> {/* No Arrow */} <IonPopover isOpen={true} arrow={false}> <IonContent>Popover Content</IonContent> </IonPopover> {/* Use a trigger */} <IonButton id="trigger-button">Click to open popover</IonButton> <IonPopover trigger="trigger-button"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Hover over trigger to open */} <IonButton id="hover-button">Hover to open popover</IonButton> <IonPopover trigger="hover-button" triggerAction="hover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Show popover above trigger */} <IonButton id="side-button">Click to open popover</IonButton> <IonPopover trigger="side-button" side="top"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Align popover to end of trigger */} <IonButton id="alignment-button">Click to open popover</IonButton> <IonPopover trigger="alignment-button" side="top" alignment="end"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover the same size as the trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" size="cover"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Make popover show relative to click coordinates rather than trigger */} <IonButton id="size-button">Click to open popover</IonButton> <IonPopover trigger="size-button" reference="event"> <IonContent>Popover Content</IonContent> </IonPopover> {/* Nested Popover */} <IonButton id="nested-button">Click to open popover</IonButton> <IonPopover trigger="nested-button" dismissOnSelect={true}> <IonContent> <ion-list> <IonItem button={true} detail={false}> <IonLabel>Option 1</IonLabel> </IonItem> <IonItem button={true} detail={false}> <IonLabel>Option 2</IonLabel> </IonItem> <IonItem button={true} detail={true} id="nested-trigger"> <IonLabel>Option 3</IonLabel> </IonItem> <IonPopover trigger="nested-trigger" dismissOnSelect={true} side="end"> <IonContent> <IonItem button={true}> <IonLabel>Nested Option</IonLabel> </IonItem> </IonContent> </IonPopover> </ion-list> </IonContent> </IonPopover> </> ); }; ``` ### Inline Popover with State ```tsx import React, { useState } from 'react'; import { IonPopover, IonButton } from '@ionic/react'; export const PopoverExample: React.FC = () => { const [popoverState, setShowPopover] = useState({ showPopover: false, event: undefined }); return ( <> <IonPopover cssClass='my-custom-class' event={popoverState.event} isOpen={popoverState.showPopover} onDidDismiss={() => setShowPopover({ showPopover: false, event: undefined })} > <p>This is popover content</p> </IonPopover> <IonButton onClick={ (e: any) => { e.persist(); setShowPopover({ showPopover: true, event: e }) }} > Show Popover </IonButton> </> ); }; ``` ### useIonPopover Hook > `useIonPopover` requires being a descendant of `<IonApp>`. If you need to use a popover outside of an `<IonApp>`, consider using the component method instead. ```tsx import React from 'react'; import { IonButton, IonContent, IonItem, IonList, IonListHeader, IonPage, useIonPopover, } from '@ionic/react'; const PopoverList: React.FC<{ onHide: () => void; }> = ({ onHide }) => ( <IonList> <IonListHeader>Ionic</IonListHeader> <IonItem button>Learn Ionic</IonItem> <IonItem button>Documentation</IonItem> <IonItem button>Showcase</IonItem> <IonItem button>GitHub Repo</IonItem> <IonItem lines="none" detail={false} button onClick={onHide}> Close </IonItem> </IonList> ); const PopoverExample: React.FC = () => { const [present, dismiss] = useIonPopover(PopoverList, { onHide: () => dismiss() }); return ( <IonPage> <IonContent> <IonButton expand="block" onClick={(e) => present({ event: e.nativeEvent, }) } > Show Popover </IonButton> </IonContent> </IonPage> ); }; ``` ### Stencil ### Inline Popover ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { render() { return [ <ion-content> {/* Default */} <ion-popover isOpen={true}> <ion-content>Popover Content</ion-content> </ion-popover> {/* No Arrow */} <ion-popover isOpen={true} arrow={false}> <ion-content>Popover Content</ion-content> </ion-popover> {/* Use a trigger */} <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Hover over trigger to open */} <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" triggerAction="hover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Show popover above trigger */} <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Align popover to end of trigger */} <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover the same size as the trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Make popover show relative to click coordinates rather than trigger */} <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> {/* Nested Popover */} <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" dismissOnSelect={true}> <ion-content> <ion-list> <ion-item button={true} detail={false}> <ion-label>Option 1</ion-label> </ion-item> <ion-item button={true} detail={false}> <ion-label>Option 2</ion-label> </ion-item> <ion-item button={true} detail={true} id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" dismissOnSelect={true} side="end"> <ion-content> <ion-item button={true}> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Popover Controller ```tsx import { Component, h } from '@stencil/core'; import { popoverController } from '@ionic/core'; @Component({ tag: 'popover-example', styleUrl: 'popover-example.css' }) export class PopoverExample { async presentPopover(ev: any) { const popover = await popoverController.create({ component: 'page-popover', cssClass: 'my-custom-class', event: ev, translucent: true }); await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); } render() { return [ <ion-content> <ion-button onClick={(ev) => this.presentPopover(ev)}>Present Popover</ion-button> </ion-content> ]; } } ``` ```tsx import { Component, h } from '@stencil/core'; @Component({ tag: 'page-popover', styleUrl: 'page-popover.css', }) export class PagePopover { render() { return [ <ion-list> <ion-item> <ion-label>Documentation</ion-label> </ion-item> <ion-item> <ion-label>Feedback</ion-label> </ion-item> <ion-item> <ion-label>Settings</ion-label> </ion-item> </ion-list> ]; } } ``` ### Vue ### Inline Popover ```html <template> <!-- Default --> <ion-popover :is-open="true"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- No Arrow --> <ion-popover :is-open="true" :arrow="false"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Use a trigger --> <ion-button id="trigger-button">Click to open popover</ion-button> <ion-popover trigger="trigger-button"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Hover over trigger to open --> <ion-button id="hover-button">Hover to open popover</ion-button> <ion-popover trigger="hover-button" trigger-action="hover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Show popover above trigger --> <ion-button id="side-button">Click to open popover</ion-button> <ion-popover trigger="side-button" side="top"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Align popover to end of trigger --> <ion-button id="alignment-button">Click to open popover</ion-button> <ion-popover trigger="alignment-button" side="top" alignment="end"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover the same size as the trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" size="cover"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Make popover show relative to click coordinates rather than trigger --> <ion-button id="size-button">Click to open popover</ion-button> <ion-popover trigger="size-button" reference="event"> <ion-content>Popover Content</ion-content> </ion-popover> <!-- Nested Popover --> <ion-button id="nested-button">Click to open popover</ion-button> <ion-popover trigger="nested-button" :dismiss-on-select="true"> <ion-content> <ion-list> <ion-item :button="true" :detail="false"> <ion-label>Option 1</ion-label> </ion-item> <ion-item :button="true" :detail="false"> <ion-label>Option 2</ion-label> </ion-item> <ion-item :button="true" :detail="true" id="nested-trigger"> <ion-label>Option 3</ion-label> </ion-item> <ion-popover trigger="nested-trigger" :dismiss-on-select="true" side="end"> <ion-content> <ion-item :button="true"> <ion-label>Nested Option</ion-label> </ion-item> </ion-content> </ion-popover> </ion-list> </ion-content> </ion-popover> </template> <script> import { IonButton, IonContent, IonItem, IonLabel, IonPopover } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ components: { IonButton, IonContent, IonItem, IonLabel, IonPopover } }); </script> ``` ### Inline Popover with State ```html <template> <ion-button @click="setOpen(true, $event)">Show Popover</ion-button> <ion-popover :is-open="isOpenRef" css-class="my-custom-class" :event="event" :translucent="true" @didDismiss="setOpen(false)" > <Popover></Popover> </ion-popover> </template> <script> import { IonButton, IonPopover } from '@ionic/vue'; import { defineComponent, ref } from 'vue'; import Popover from './popover.vue'; export default defineComponent({ components: { IonButton, IonPopover, Popover }, setup() { const isOpenRef = ref(false); const event = ref(); const setOpen = (state: boolean, ev?: Event) => { event.value = ev; isOpenRef.value = state; } return { isOpenRef, setOpen, event } } }); </script> ``` ### Popover Controller ```html <template> <ion-content class="ion-padding"> Popover Content </ion-content> </template> <script> import { IonContent } from '@ionic/vue'; import { defineComponent } from 'vue'; export default defineComponent({ name: 'Popover', components: { IonContent } }); </script> ``` ```html <template> <ion-page> <ion-content class="ion-padding"> <ion-button @click="openPopover">Open Popover</ion-button> </ion-content> </ion-page> </template> <script> import { IonButton, IonContent, IonPage, popoverController } from '@ionic/vue'; import Popover from './popover.vue'; export default { components: { IonButton, IonContent, IonPage }, methods: { async openPopover(ev: Event) { const popover = await popoverController .create({ component: Popover, cssClass: 'my-custom-class', event: ev, translucent: true }) await popover.present(); const { role } = await popover.onDidDismiss(); console.log('onDidDismiss resolved with role', role); }, }, } </script> ``` ## Properties | Property | Attribute | Description | Type | Default | | ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------- | | `alignment` | `alignment` | Describes how to align the popover content with the `reference` point. Defaults to `'center'` for `ios` mode, and `'start'` for `md` mode. | `"center" \| "end" \| "start" \| undefined` | `undefined` | | `animated` | `animated` | If `true`, the popover will animate. | `boolean` | `true` | | `arrow` | `arrow` | If `true`, the popover will display an arrow that points at the `reference` when running in `ios` mode on mobile. Does not apply in `md` mode or on desktop. | `boolean` | `true` | | `backdropDismiss` | `backdrop-dismiss` | If `true`, the popover will be dismissed when the backdrop is clicked. | `boolean` | `true` | | `component` | `component` | The component to display inside of the popover. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just slot your component inside of `ion-popover`. | `Function \| HTMLElement \| null \| string \| undefined` | `undefined` | | `componentProps` | -- | The data to pass to the popover component. You only need to use this if you are not using a JavaScript framework. Otherwise, you can just set the props directly on your component. | `undefined \| { [key: string]: any; }` | `undefined` | | `dismissOnSelect` | `dismiss-on-select` | If `true`, the popover will be automatically dismissed when the content has been clicked. | `boolean` | `false` | | `enterAnimation` | -- | Animation to use when the popover is presented. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `event` | `event` | The event to pass to the popover animation. | `any` | `undefined` | | `htmlAttributes` | -- | Additional attributes to pass to the popover. | `PopoverAttributes \| undefined` | `undefined` | | `isOpen` | `is-open` | If `true`, the popover will open. If `false`, the popover will close. Use this if you need finer grained control over presentation, otherwise just use the popoverController or the `trigger` property. Note: `isOpen` will not automatically be set back to `false` when the popover dismisses. You will need to do that in your code. | `boolean` | `false` | | `keyboardClose` | `keyboard-close` | If `true`, the keyboard will be automatically dismissed when the overlay is presented. | `boolean` | `true` | | `leaveAnimation` | -- | Animation to use when the popover is dismissed. | `((baseEl: any, opts?: any) => Animation) \| undefined` | `undefined` | | `mode` | `mode` | The mode determines which platform styles to use. | `"ios" \| "md"` | `undefined` | | `reference` | `reference` | Describes what to position the popover relative to. If `'trigger'`, the popover will be positioned relative to the trigger button. If passing in an event, this is determined via event.target. If `'event'`, the popover will be positioned relative to the x/y coordinates of the trigger action. If passing in an event, this is determined via event.clientX and event.clientY. | `"event" \| "trigger"` | `'trigger'` | | `showBackdrop` | `show-backdrop` | If `true`, a backdrop will be displayed behind the popover. | `boolean` | `true` | | `side` | `side` | Describes which side of the `reference` point to position the popover on. The `'start'` and `'end'` values are RTL-aware, and the `'left'` and `'right'` values are not. | `"bottom" \| "end" \| "left" \| "right" \| "start" \| "top"` | `'bottom'` | | `size` | `size` | Describes how to calculate the popover width. If `'cover'`, the popover width will match the width of the trigger. If `'auto'`, the popover width will be determined by the content in the popover. | `"auto" \| "cover"` | `'auto'` | | `translucent` | `translucent` | If `true`, the popover will be translucent. Only applies when the mode is `"ios"` and the device supports [`backdrop-filter`](https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter#Browser_compatibility). | `boolean` | `false` | | `trigger` | `trigger` | An ID corresponding to the trigger element that causes the popover to open. Use the `trigger-action` property to customize the interaction that results in the popover opening. | `string \| undefined` | `undefined` | | `triggerAction` | `trigger-action` | Describes what kind of interaction with the trigger that should cause the popover to open. Does not apply when the `trigger` property is `undefined`. If `'click'`, the popover will be presented when the trigger is left clicked. If `'hover'`, the popover will be presented when a pointer hovers over the trigger. If `'context-menu'`, the popover will be presented when the trigger is right clicked on desktop and long pressed on mobile. This will also prevent your device's normal context menu from appearing. | `"click" \| "context-menu" \| "hover"` | `'click'` | ## Events | Event | Description | Type | | ----------------------- | ------------------------------------------------------------------------------ | -------------------------------------- | | `didDismiss` | Emitted after the popover has dismissed. Shorthand for ionPopoverDidDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `didPresent` | Emitted after the popover has presented. Shorthand for ionPopoverWillDismiss. | `CustomEvent<void>` | | `ionPopoverDidDismiss` | Emitted after the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverDidPresent` | Emitted after the popover has presented. | `CustomEvent<void>` | | `ionPopoverWillDismiss` | Emitted before the popover has dismissed. | `CustomEvent<OverlayEventDetail<any>>` | | `ionPopoverWillPresent` | Emitted before the popover has presented. | `CustomEvent<void>` | | `willDismiss` | Emitted before the popover has dismissed. Shorthand for ionPopoverWillDismiss. | `CustomEvent<OverlayEventDetail<any>>` | | `willPresent` | Emitted before the popover has presented. Shorthand for ionPopoverWillPresent. | `CustomEvent<void>` | ## Methods ### `dismiss(data?: any, role?: string | undefined, dismissParentPopover?: boolean) => Promise<boolean>` Dismiss the popover overlay after it has been presented. #### Returns Type: `Promise<boolean>` ### `onDidDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover did dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `onWillDismiss<T = any>() => Promise<OverlayEventDetail<T>>` Returns a promise that resolves when the popover will dismiss. #### Returns Type: `Promise<OverlayEventDetail<T>>` ### `present(event?: MouseEvent | TouchEvent | PointerEvent | CustomEvent<any> | undefined) => Promise<void>` Present the popover overlay after it has been created. Developers can pass a mouse, touch, or pointer event to position the popover relative to where that event was dispatched. #### Returns Type: `Promise<void>` ## Slots | Slot | Description | | ---- | ----------------------------------------------------------- | | | Content is placed inside of the `.popover-content` element. | ## Shadow Parts | Part | Description | | ------------ | --------------------------------------------------------------------------- | | `"arrow"` | The arrow that points to the reference element. Only applies on `ios` mode. | | `"backdrop"` | The `ion-backdrop` element. | | `"content"` | The wrapper element for the default slot. | ## CSS Custom Properties | Name | Description | | -------------------- | ----------------------------------------------- | | `--backdrop-opacity` | Opacity of the backdrop | | `--background` | Background of the popover | | `--box-shadow` | Box shadow of the popover | | `--height` | Height of the popover | | `--max-height` | Maximum height of the popover | | `--max-width` | Maximum width of the popover | | `--min-height` | Minimum height of the popover | | `--min-width` | Minimum width of the popover | | `--offset-x` | The amount to move the popover by on the x-axis | | `--offset-y` | The amount to move the popover by on the y-axis | | `--width` | Width of the popover | ## Dependencies ### Used by - [ion-datetime](../datetime) ### Depends on - [ion-backdrop](../backdrop) ### Graph ```mermaid graph TD; ion-popover --> ion-backdrop ion-datetime --> ion-popover style ion-popover fill:#f9f,stroke:#333,stroke-width:4px ``` ---------------------------------------------- *Built with [StencilJS](https://stenciljs.com/)*
core/src/components/popover/readme.md
1
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00425751693546772, 0.00030679034534841776, 0.00016147911082953215, 0.00017019824008457363, 0.0004678302793763578 ]
{ "id": 8, "code_window": [ " ion-item --> ion-icon\n", " ion-item --> ion-ripple-effect\n", " ion-item --> ion-note\n", " style ion-select fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-popover --> ion-backdrop\n", " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1015 }
package com.getcapacitor.myapp; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
packages/react-router/test-app/android/app/src/test/java/com/getcapacitor/myapp/ExampleUnitTest.java
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.00017529337492305785, 0.00017507444135844707, 0.0001748555077938363, 0.00017507444135844707, 2.1893356461077929e-7 ]
{ "id": 8, "code_window": [ " ion-item --> ion-icon\n", " ion-item --> ion-ripple-effect\n", " ion-item --> ion-note\n", " style ion-select fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-popover --> ion-backdrop\n", " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1015 }
import { newE2EPage } from '@stencil/core/testing'; test('icon: standalone', async () => { const page = await newE2EPage({ url: '/src/components/icon/test/standalone?ionic:_testing=true' }); const compare = await page.compareScreenshot(); expect(compare).toMatchScreenshot(); });
core/src/components/icon/test/standalone/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0001768191286828369, 0.00017299798491876572, 0.00016917684115469456, 0.00017299798491876572, 0.0000038211437640711665 ]
{ "id": 8, "code_window": [ " ion-item --> ion-icon\n", " ion-item --> ion-ripple-effect\n", " ion-item --> ion-note\n", " style ion-select fill:#f9f,stroke:#333,stroke-width:4px\n", "```\n", "\n", "----------------------------------------------\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ " ion-popover --> ion-backdrop\n", " ion-action-sheet --> ion-backdrop\n", " ion-action-sheet --> ion-icon\n", " ion-action-sheet --> ion-ripple-effect\n", " ion-alert --> ion-ripple-effect\n", " ion-alert --> ion-backdrop\n" ], "file_path": "core/src/components/select/readme.md", "type": "add", "edit_start_line_idx": 1015 }
import { newE2EPage } from '@stencil/core/testing'; test('router: basic', async () => { const page = await newE2EPage({ url: '/src/components/router/test/basic?ionic:_testing=true' }); const compare = await page.compareScreenshot(); expect(compare).toMatchScreenshot(); });
core/src/components/router/test/basic/e2e.ts
0
https://github.com/ionic-team/ionic-framework/commit/65b43aae2b42f390b7d1e9738a7e4f94db005f03
[ 0.0001768191286828369, 0.00017582648433744907, 0.00017483382544014603, 0.00017582648433744907, 9.926516213454306e-7 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.6\n", "\n", "import { Component } from 'react';\n", "import { Options } from 'flatpickr';\n", "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
import { Instance } from 'flatpickr'; import * as React from 'react'; import DatePicker from 'react-flatpickr'; const noParamsElement = <DatePicker/>; const defaultValueElement = <DatePicker defaultValue={ 'Default value' }/>; const options = { dateFormat: 'YYYY-MM-DD' }; const optionsElement = <DatePicker options={ options }/>; const onChange = ( selectedDates: Date[], dateStr: string, instance: Instance, elem: HTMLElement ) => null; const onChangeElement = <DatePicker onChange={ onChange }/>; const valueElement = <DatePicker value={ 'Value' }/>;
types/react-flatpickr/react-flatpickr-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.0013485318049788475, 0.0005845558480359614, 0.00017668279178906232, 0.0002284528745803982, 0.0005406258860602975 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.6\n", "\n", "import { Component } from 'react';\n", "import { Options } from 'flatpickr';\n", "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
// Type definitions for zipcodes 6.0 // Project: https://github.com/davglass/zipcodes#readme // Definitions by: Brayden Lopez <https://github.com/headdetect> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace ZipCodes; export interface ZipCode { zip: string; latitude: number; longitude: number; city: string; state: string; country: string; } export function lookup(zip: any): ZipCode; export function lookupByName(city: string, state: string): ZipCode[]; export function lookupByState(state: string): ZipCode[]; export function distance(zipA: ZipCode, zipB: ZipCode): number; export function radius(zip: ZipCode, miles: number, full: boolean): string | ZipCode[]; export function toMiles(kilos: number): number; export function toKilometers(miles: number): number; export function lookupByCoords(lat: number, lon: number): ZipCode;
types/zipcodes/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00038515948108397424, 0.0002215013955719769, 0.000163926713867113, 0.00016845969366841018, 0.00009452788799535483 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.6\n", "\n", "import { Component } from 'react';\n", "import { Options } from 'flatpickr';\n", "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "ssh2-sftp-client-tests.ts" ] }
types/ssh2-sftp-client/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00017407049017492682, 0.00017210132500622422, 0.0001705880422377959, 0.00017164548626169562, 0.0000014577866522813565 ]
{ "id": 0, "code_window": [ "// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped\n", "// TypeScript Version: 2.6\n", "\n", "import { Component } from 'react';\n", "import { Options } from 'flatpickr';\n", "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 7 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "fb-tests.ts" ] }
types/fb/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00017193164967466146, 0.00017137790564447641, 0.0001709140051389113, 0.00017128809122368693, 4.202787806661945e-7 ]
{ "id": 1, "code_window": [ "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n", " options?: Options.Options;\n", " onChange?: Options.Hook;\n", " value?: string;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " options?: flatpickr.Options.Options;\n", " onChange?: flatpickr.Options.Hook;\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
import { Instance } from 'flatpickr'; import * as React from 'react'; import DatePicker from 'react-flatpickr'; const noParamsElement = <DatePicker/>; const defaultValueElement = <DatePicker defaultValue={ 'Default value' }/>; const options = { dateFormat: 'YYYY-MM-DD' }; const optionsElement = <DatePicker options={ options }/>; const onChange = ( selectedDates: Date[], dateStr: string, instance: Instance, elem: HTMLElement ) => null; const onChangeElement = <DatePicker onChange={ onChange }/>; const valueElement = <DatePicker value={ 'Value' }/>;
types/react-flatpickr/react-flatpickr-tests.tsx
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.0037252178881317377, 0.0023940878454595804, 0.00017844424291979522, 0.0032786012161523104, 0.001577270682901144 ]
{ "id": 1, "code_window": [ "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n", " options?: Options.Options;\n", " onChange?: Options.Hook;\n", " value?: string;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " options?: flatpickr.Options.Options;\n", " onChange?: flatpickr.Options.Hook;\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
// Type definitions for zipkin-instrumentation-express 0.11 // Project: https://github.com/openzipkin/zipkin-js#readme // Definitions by: York Yao <https://github.com/plantain-00> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 import express = require('express'); import { Tracer } from 'zipkin'; export interface Options { tracer: Tracer; } export function expressMiddleware(options: Options): express.RequestHandler;
types/zipkin-instrumentation-express/index.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.002906017703935504, 0.001755864592269063, 0.0006057115970179439, 0.001755864592269063, 0.001150153111666441 ]
{ "id": 1, "code_window": [ "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n", " options?: Options.Options;\n", " onChange?: Options.Hook;\n", " value?: string;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " options?: flatpickr.Options.Options;\n", " onChange?: flatpickr.Options.Hook;\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoAndroidApps extends React.Component<IconBaseProps> { }
types/react-icons/io/android-apps.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00016912522551137954, 0.00016912522551137954, 0.00016912522551137954, 0.00016912522551137954, 0 ]
{ "id": 1, "code_window": [ "\n", "export interface DateTimePickerProps {\n", " defaultValue?: string;\n", " options?: Options.Options;\n", " onChange?: Options.Hook;\n", " value?: string;\n", "}\n", "\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [ " options?: flatpickr.Options.Options;\n", " onChange?: flatpickr.Options.Hook;\n" ], "file_path": "types/react-flatpickr/index.d.ts", "type": "replace", "edit_start_line_idx": 11 }
import which = require("which"); which("cat", (err, path) => { console.log(path); }); var path = which.sync("cat"); console.log(path); which("cat", {all: true}, (err, paths) => { if(err) return; if(paths) { for(let path of paths) { console.log(path); } } }); var paths = which.sync("cat", {all: true}); for(let path of paths) { console.log(path); } var paths2 = which.sync("cat", {all: true, nothrow: true}); if(paths2 !== null) { for(let path of paths2) { console.log(path); } } var path2 = which.sync("cat", {path: 'replacement path', pathExt: 'replacement pathext'}); which("cat", {path: 'replacement path', pathExt: 'replacement pathext'}, (err, path) => { const a: string = path!; });
types/which/which-tests.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.0002542935835663229, 0.00019314332166686654, 0.00017113692592829466, 0.00017357135948259383, 0.000035319117159815505 ]
{ "id": 2, "code_window": [ "import { Instance } from 'flatpickr';\n", "import * as React from 'react';\n", "import DatePicker from 'react-flatpickr';\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 0 }
// Type definitions for react-flatpickr 3.2 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar <https://github.com/begincalendar> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 import { Component } from 'react'; import { Options } from 'flatpickr'; export interface DateTimePickerProps { defaultValue?: string; options?: Options.Options; onChange?: Options.Hook; value?: string; } export default class DatePicker extends Component<DateTimePickerProps> {}
types/react-flatpickr/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.002115813083946705, 0.0014270266983658075, 0.0007382403709925711, 0.0014270266983658075, 0.0006887863855808973 ]
{ "id": 2, "code_window": [ "import { Instance } from 'flatpickr';\n", "import * as React from 'react';\n", "import DatePicker from 'react-flatpickr';\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 0 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoIosPersonaddOutline extends React.Component<IconBaseProps> { }
types/react-icons/io/ios-personadd-outline.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00025861026369966567, 0.00025861026369966567, 0.00025861026369966567, 0.00025861026369966567, 0 ]
{ "id": 2, "code_window": [ "import { Instance } from 'flatpickr';\n", "import * as React from 'react';\n", "import DatePicker from 'react-flatpickr';\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 0 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class MdMovieFilter extends React.Component<IconBaseProps> { }
types/react-icons/md/movie-filter.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00023912967299111187, 0.00023912967299111187, 0.00023912967299111187, 0.00023912967299111187, 0 ]
{ "id": 2, "code_window": [ "import { Instance } from 'flatpickr';\n", "import * as React from 'react';\n", "import DatePicker from 'react-flatpickr';\n", "\n" ], "labels": [ "replace", "keep", "keep", "keep" ], "after_edit": [ "import flatpickr from 'flatpickr';\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 0 }
{ "extends": "dtslint/dt.json" }
types/lodash.snakecase/tslint.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00017140213458333164, 0.00017140213458333164, 0.00017140213458333164, 0.00017140213458333164, 0 ]
{ "id": 3, "code_window": [ " dateFormat: 'YYYY-MM-DD'\n", "};\n", "const optionsElement = <DatePicker options={ options }/>;\n", "\n", "const onChange = (\n", " selectedDates: Date[], dateStr: string, instance: Instance,\n", " elem: HTMLElement\n", ") => null;\n", "const onChangeElement = <DatePicker onChange={ onChange }/>;\n", "\n", "const valueElement = <DatePicker value={ 'Value' }/>;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " selectedDates: Date[], dateStr: string, instance: flatpickr.Instance,\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 14 }
// Type definitions for react-flatpickr 3.2 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar <https://github.com/begincalendar> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 import { Component } from 'react'; import { Options } from 'flatpickr'; export interface DateTimePickerProps { defaultValue?: string; options?: Options.Options; onChange?: Options.Hook; value?: string; } export default class DatePicker extends Component<DateTimePickerProps> {}
types/react-flatpickr/index.d.ts
1
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.001560413627885282, 0.0008630696102045476, 0.00016572559252381325, 0.0008630696102045476, 0.0006973440176807344 ]
{ "id": 3, "code_window": [ " dateFormat: 'YYYY-MM-DD'\n", "};\n", "const optionsElement = <DatePicker options={ options }/>;\n", "\n", "const onChange = (\n", " selectedDates: Date[], dateStr: string, instance: Instance,\n", " elem: HTMLElement\n", ") => null;\n", "const onChangeElement = <DatePicker onChange={ onChange }/>;\n", "\n", "const valueElement = <DatePicker value={ 'Value' }/>;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " selectedDates: Date[], dateStr: string, instance: flatpickr.Instance,\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 14 }
// Type definitions for murmurhash-js v1.0.0 // Project: https://github.com/mikolalysenko/murmurhash-js // Definitions by: Chi Vinh Le <https://github.com/cvle> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare const murmur: (str: string, seed?: number) => number; export = murmur;
types/murmurhash-js/murmurhash3_gc.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00017251941608265042, 0.00017251941608265042, 0.00017251941608265042, 0.00017251941608265042, 0 ]
{ "id": 3, "code_window": [ " dateFormat: 'YYYY-MM-DD'\n", "};\n", "const optionsElement = <DatePicker options={ options }/>;\n", "\n", "const onChange = (\n", " selectedDates: Date[], dateStr: string, instance: Instance,\n", " elem: HTMLElement\n", ") => null;\n", "const onChangeElement = <DatePicker onChange={ onChange }/>;\n", "\n", "const valueElement = <DatePicker value={ 'Value' }/>;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " selectedDates: Date[], dateStr: string, instance: flatpickr.Instance,\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 14 }
{ "compilerOptions": { "module": "commonjs", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" ], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", "imagesloaded-tests.ts" ] }
types/imagesloaded/tsconfig.json
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.00017552969802636653, 0.00017419889627490193, 0.00017335130542051047, 0.00017371567082591355, 9.527067277304013e-7 ]
{ "id": 3, "code_window": [ " dateFormat: 'YYYY-MM-DD'\n", "};\n", "const optionsElement = <DatePicker options={ options }/>;\n", "\n", "const onChange = (\n", " selectedDates: Date[], dateStr: string, instance: Instance,\n", " elem: HTMLElement\n", ") => null;\n", "const onChangeElement = <DatePicker onChange={ onChange }/>;\n", "\n", "const valueElement = <DatePicker value={ 'Value' }/>;" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " selectedDates: Date[], dateStr: string, instance: flatpickr.Instance,\n" ], "file_path": "types/react-flatpickr/react-flatpickr-tests.tsx", "type": "replace", "edit_start_line_idx": 14 }
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; declare class TiZoom extends React.Component<IconBaseProps> { } export = TiZoom;
types/react-icons/lib/ti/zoom.d.ts
0
https://github.com/DefinitelyTyped/DefinitelyTyped/commit/cc06c0bd237623a251bbd41fe4696321533e7a3b
[ 0.0001748163194861263, 0.0001748163194861263, 0.0001748163194861263, 0.0001748163194861263, 0 ]
{ "id": 0, "code_window": [ "import { Button, IconDownload, IconPlus, IconX, IconTrash } from '@supabase/ui'\n", "import { saveAs } from 'file-saver'\n", "\n", "import FilterDropdown from './filter'\n", "import SortPopover from './sort'\n", "import StatusLabel from './StatusLabel'\n", "import RefreshButton from './RefreshButton'\n", "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { useStore } from 'hooks'\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 4 }
import { IRowService } from '.' import { Filter, ServiceError, Sort, SupaRow, SupaTable } from '../../types' import { ERROR_PRIMARY_KEY_NOTFOUND, SupabaseGridQueue } from '../../constants' import Query from '../../query' import { isNumericalColumn } from '../../utils' import { useDispatch } from 'components/grid/store' export class SqlRowService implements IRowService { protected query = new Query() protected dispatch = useDispatch() constructor( protected table: SupaTable, protected onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>, protected onError: (error: any) => void ) {} async count(filters: Filter[]) { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).count() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) const query = queryChains.toSql() const { data, error } = await this.onSqlQuery(query) if (error) { return { error } } else { if (data?.length == 1) { return { data: data[0].count } } else { return { error: { message: 'fetch rows count failed' } } } } } async create(row: SupaRow) { return { error: { message: 'not implemented' } } } delete(rows: SupaRow[]) { const { primaryKeys, error } = this.getPrimaryKeys() if (error) return { error } let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).delete() primaryKeys!.forEach((key) => { const primaryKeyValues = rows.map((x) => x[key]) queryChains = queryChains.filter(key, 'in', primaryKeyValues) }) const query = queryChains.toSql() SupabaseGridQueue.add(async () => { const { error } = await this.onSqlQuery(query) if (error) throw error }).catch((error) => { this.onError(error) }) return {} } // For deleting all rows based on a given filter async deleteAll(filters: Filter[]) { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).delete() filters .filter((x) => x.value && x.value !== '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) const query = queryChains.toSql() return await this.onSqlQuery(query) } // For deleting all rows without any filter (clear entire table) async truncate() { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).truncate() const query = queryChains.toSql() return await this.onSqlQuery(query) } async fetchPage(page: number, rowsPerPage: number, filters: Filter[], sorts: Sort[]) { const pageFromZero = page > 0 ? page - 1 : page const from = pageFromZero * rowsPerPage const to = (pageFromZero + 1) * rowsPerPage - 1 let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) sorts.forEach((x) => { queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst) }) const query = queryChains.range(from, to).toSql() const { data, error } = await this.onSqlQuery(query) if (error) { this.onError(error) return { data: { rows: [] } } } else { const rows = data?.map((x: any, index: number) => { return { idx: index, ...x } as SupaRow }) return { data: { rows } } } } async fetchAllData(filters: Filter[], sorts: Sort[]) { // Paginate the request for very large tables to prevent stalling of API // [TODO] Note we probably still need a fail-safe if the table is just // too large for a browser to keep all the rows in memory before exporting // Either that or export as multiple CSV sheets, max n rows const rows: any[] = [] let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) sorts.forEach((x) => { queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst) }) // Starting from page 0, fetch 500 records per call let page = -1 let from = 0 let to = 0 let pageData = [] const rowsPerPage = 500 await (async () => { do { page += 1 from = page * rowsPerPage to = (page + 1) * rowsPerPage - 1 const query = queryChains.range(from, to).toSql() const { data, error } = await this.onSqlQuery(query) if (error) { this.onError(error) return { data: { rows: [] } } } else { rows.push(...data) pageData = data } } while (pageData.length === rowsPerPage) })() return rows } update(row: SupaRow, changedColumn?: string, onRowUpdate?: (value: any) => void) { const { primaryKeys, error } = this.getPrimaryKeys() if (error) { return { error } } const { idx, ...value } = row const matchValues: any = {} primaryKeys!.forEach((key) => { matchValues[key] = row[key] // fix: https://github.com/supabase/grid/issues/94 // remove primary key from updated value object delete value[key] }) const query = this.query .from(this.table.name, this.table.schema ?? undefined) .update( changedColumn ? { [changedColumn]: value[changedColumn], } : value, { returning: true } ) .match(matchValues) .toSql() SupabaseGridQueue.add(async () => { const { data, error } = await this.onSqlQuery(query) if (error) throw error if (onRowUpdate) onRowUpdate({ row: data[0], idx }) }).catch((error) => { this.onError(error) }) return {} } getPrimaryKeys(): { primaryKeys?: string[]; error?: ServiceError } { const pkColumns = this.table.columns.filter((x) => x.isPrimaryKey) if (!pkColumns || pkColumns.length == 0) { return { error: { message: ERROR_PRIMARY_KEY_NOTFOUND } } } return { primaryKeys: pkColumns.map((x) => x.name) } } /** * temporary fix until we impliment a better filter UI * which validate input value base on the column type */ formatFilterValue(filter: Filter) { const column = this.table.columns.find((x) => x.name == filter.column) if (column && isNumericalColumn(column.format)) { const numberValue = Number(filter.value) if (Number.isNaN(numberValue)) return filter.value else return Number(filter.value) } return filter.value } }
studio/components/grid/services/row/SqlRowService.ts
1
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0007131405873224139, 0.00021874513186048716, 0.00016207870794460177, 0.00016913538274820894, 0.00012224161764606833 ]
{ "id": 0, "code_window": [ "import { Button, IconDownload, IconPlus, IconX, IconTrash } from '@supabase/ui'\n", "import { saveAs } from 'file-saver'\n", "\n", "import FilterDropdown from './filter'\n", "import SortPopover from './sort'\n", "import StatusLabel from './StatusLabel'\n", "import RefreshButton from './RefreshButton'\n", "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { useStore } from 'hooks'\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 4 }
--- id: using-filters title: "Using Filters" slug: using-filters custom_edit_url: https://github.com/supabase/supabase/edit/master/web/spec/supabase.yml --- import Tabs from '@theme/Tabs'; import TabsPanel from '@theme/TabsPanel'; Filters can be used on `select()`, `update()`, and `delete()` queries. If a Postgres function returns a table response, you can also apply filters. ### Applying Filters You must apply your filters to the end of your query. For example: ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .eq('name', 'The Shire') // Correct const { data, error } = await supabase .from('cities') .eq('name', 'The Shire') // Incorrect .select('name, country_id') ``` ### Chaining Filters can be chained together to produce advanced queries. For example: ```js const { data, error } = await supabase .from('cities') .select('name, country_id') .gte('population', 1000) .lt('population', 10000) ``` ### Conditional Chaining Filters can be built up one step at a time and then executed. For example: ```js const filterByName = null const filterPopLow = 1000 const filterPopHigh = 10000 let query = supabase .from('cities') .select('name, country_id') if (filterByName) { query = query.eq('name', filterByName) } if (filterPopLow) { query = query.gte('population', filterPopLow) } if (filterPopHigh) { query = query.lt('population', filterPopHigh) } const { data, error } = await query ```
apps/temp-docs/docs/reference/javascript/using-filters.mdx
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0010483090300112963, 0.00031906410004012287, 0.00016606933786533773, 0.0001872524298960343, 0.00030068386695347726 ]
{ "id": 0, "code_window": [ "import { Button, IconDownload, IconPlus, IconX, IconTrash } from '@supabase/ui'\n", "import { saveAs } from 'file-saver'\n", "\n", "import FilterDropdown from './filter'\n", "import SortPopover from './sort'\n", "import StatusLabel from './StatusLabel'\n", "import RefreshButton from './RefreshButton'\n", "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { useStore } from 'hooks'\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 4 }
{ "name": "supabase-slack-clone-basic", "version": "0.1.1", "license": "MIT", "scripts": { "dev": "next", "export": "next export", "build": "next build", "start": "next start" }, "dependencies": { "@supabase/supabase-js": "^1.35.3", "next": "latest", "react": "^18.0.0", "react-dom": "^18.0.0", "sass": "^1.26.2", "tailwindcss": "^1.1.4" } }
examples/slack-clone/nextjs-slack-clone/package.json
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0001659001427469775, 0.00016546272672712803, 0.00016502531070727855, 0.00016546272672712803, 4.374160198494792e-7 ]
{ "id": 0, "code_window": [ "import { Button, IconDownload, IconPlus, IconX, IconTrash } from '@supabase/ui'\n", "import { saveAs } from 'file-saver'\n", "\n", "import FilterDropdown from './filter'\n", "import SortPopover from './sort'\n", "import StatusLabel from './StatusLabel'\n", "import RefreshButton from './RefreshButton'\n", "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "import { useStore } from 'hooks'\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 4 }
// Just extracting the color configuration to a single file so that it's easier to observe // Needs better naming to be honest, but just to get things going // For ChartHandler export const CHART_COLORS = { TICK: 'var(--colors-scale6)', AXIS: 'var(--colors-scale6)', GREEN_1: 'var(--colors-brand9)', // #3ECF8E GREEN_2: 'var(--colors-brand6)', } export const USAGE_COLORS = { 200: 'var(--colors-brand9)', 201: 'var(--colors-brand8)', 400: 'var(--colors-amber9)', 401: 'var(--colors-amber8)', 404: 'var(--colors-amber7)', 500: 'var(--colors-red9)', }
studio/components/ui/Charts/Charts.constants.ts
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0019238922977820039, 0.001054604072123766, 0.00018531583191361278, 0.001054604072123766, 0.0008692882256582379 ]
{ "id": 1, "code_window": [ "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n", "import { Sort, Filter } from 'components/grid/types'\n", "import { exportRowsToCsv } from 'components/grid/utils'\n", "import { useDispatch, useTrackedState } from 'components/grid/store'\n", "\n", "interface HeaderProps {\n", " sorts: Sort[]\n", " filters: Filter[]\n", " onAddColumn?: () => void\n", " onAddRow?: () => void\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// [Joshen] CSV exports require this guard as a fail-safe if the table is\n", "// just too large for a browser to keep all the rows in memory before\n", "// exporting. Either that or export as multiple CSV sheets with max n rows each\n", "const MAX_EXPORT_ROW_COUNT = 500000\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 13 }
import { FC, useState, ReactNode } from 'react' import { Button, IconDownload, IconPlus, IconX, IconTrash } from '@supabase/ui' import { saveAs } from 'file-saver' import FilterDropdown from './filter' import SortPopover from './sort' import StatusLabel from './StatusLabel' import RefreshButton from './RefreshButton' import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal' import { Sort, Filter } from 'components/grid/types' import { exportRowsToCsv } from 'components/grid/utils' import { useDispatch, useTrackedState } from 'components/grid/store' interface HeaderProps { sorts: Sort[] filters: Filter[] onAddColumn?: () => void onAddRow?: () => void headerActions?: ReactNode } const Header: FC<HeaderProps> = ({ sorts, filters, onAddColumn, onAddRow, headerActions }) => { const state = useTrackedState() const { selectedRows } = state return ( <div className="bg-scale-100 dark:bg-scale-300 flex h-10 items-center justify-between px-5"> {selectedRows.size > 0 ? ( <RowHeader sorts={sorts} filters={filters} /> ) : ( <DefaultHeader sorts={sorts} filters={filters} onAddColumn={onAddColumn} onAddRow={onAddRow} /> )} <div className="sb-grid-header__inner"> {headerActions} <StatusLabel /> </div> </div> ) } export default Header interface DefaultHeaderProps { sorts: Sort[] filters: Filter[] onAddColumn?: () => void onAddRow?: () => void } const DefaultHeader: FC<DefaultHeaderProps> = ({ sorts, filters, onAddColumn, onAddRow }) => { const renderNewColumn = (onAddColumn?: () => void) => { if (!onAddColumn) return null return ( <Button type="text" onClick={onAddColumn}> New Column </Button> ) } const renderAddRow = (onAddRow?: () => void) => { if (!onAddRow) return null return ( <Button size="tiny" icon={<IconPlus size={14} strokeWidth={2} />} onClick={onAddRow}> Insert row </Button> ) } return ( <div className="flex items-center gap-4"> <div className="flex items-center gap-1"> <RefreshButton filters={filters} sorts={sorts} /> <FilterDropdown /> <SortPopover /> </div> <div className="bg-scale-600 h-[50%] w-px"></div> <div className="flex items-center gap-2"> {renderNewColumn(onAddColumn)} {renderAddRow(onAddRow)} </div> </div> ) } interface RowHeaderProps { sorts: Sort[] filters: Filter[] } const RowHeader: FC<RowHeaderProps> = ({ sorts, filters }) => { const state = useTrackedState() const dispatch = useDispatch() const [isExporting, setIsExporting] = useState(false) const { selectedRows, rows: allRows, editable, allRowsSelected, totalRows } = state const onSelectAllRows = () => { dispatch({ type: 'SELECT_ALL_ROWS', payload: { selectedRows: new Set(allRows.map((row) => row.idx)) }, }) } const onRowsDelete = () => { confirmAlert({ title: 'Confirm to delete', message: 'Are you sure you want to delete the selected rows? This action cannot be undone.', onAsyncConfirm: async () => { if (allRowsSelected) { const { error } = filters.length === 0 ? await state.rowService!.truncate() : await state.rowService!.deleteAll(filters) if (error) { if (state.onError) state.onError(error) } else { dispatch({ type: 'REMOVE_ALL_ROWS' }) dispatch({ type: 'SELECTED_ROWS_CHANGE', payload: { selectedRows: new Set() }, }) } } else { const rowIdxs = Array.from(selectedRows) as number[] const rows = allRows.filter((x) => rowIdxs.includes(x.idx)) const { error } = state.rowService!.delete(rows) if (error) { if (state.onError) state.onError(error) } else { dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs } }) dispatch({ type: 'SELECTED_ROWS_CHANGE', payload: { selectedRows: new Set() }, }) } } }, }) } async function onRowsExportCSV() { setIsExporting(true) const rows = allRowsSelected ? await state.rowService!.fetchAllData(filters, sorts) : allRows.filter((x) => selectedRows.has(x.idx)) const csv = exportRowsToCsv(state.table!.columns, rows) const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' }) saveAs(csvData, `${state.table!.name}_rows.csv`) setIsExporting(false) } function deselectRows() { dispatch({ type: 'SELECTED_ROWS_CHANGE', payload: { selectedRows: new Set() }, }) } return ( <div className="flex items-center gap-6"> <div className="flex items-center gap-3"> <Button type="default" style={{ padding: '3px' }} icon={<IconX size="tiny" strokeWidth={2} />} onClick={deselectRows} /> <span className="text-scale-1200 text-xs"> {allRowsSelected ? `${totalRows} rows selected` : selectedRows.size > 1 ? `${selectedRows.size} rows selected` : `${selectedRows.size} row selected`} </span> {!allRowsSelected && ( <Button type="link" onClick={() => onSelectAllRows()}> Select all {totalRows} rows </Button> )} </div> <div className="h-[20px] border-r border-gray-700" /> <div className="flex items-center gap-2"> <Button type="primary" size="tiny" icon={<IconDownload />} loading={isExporting} disabled={isExporting} onClick={onRowsExportCSV} > Export to CSV </Button> {editable && ( <Button type="default" size="tiny" icon={<IconTrash size="tiny" />} onClick={onRowsDelete} > {allRowsSelected ? `Delete ${totalRows} rows` : selectedRows.size > 1 ? `Delete ${selectedRows.size} rows` : `Delete ${selectedRows.size} row`} </Button> )} </div> </div> ) }
studio/components/grid/components/header/Header.tsx
1
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.9980644583702087, 0.21289990842342377, 0.00016390781092923135, 0.0015377533854916692, 0.36913344264030457 ]
{ "id": 1, "code_window": [ "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n", "import { Sort, Filter } from 'components/grid/types'\n", "import { exportRowsToCsv } from 'components/grid/utils'\n", "import { useDispatch, useTrackedState } from 'components/grid/store'\n", "\n", "interface HeaderProps {\n", " sorts: Sort[]\n", " filters: Filter[]\n", " onAddColumn?: () => void\n", " onAddRow?: () => void\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// [Joshen] CSV exports require this guard as a fail-safe if the table is\n", "// just too large for a browser to keep all the rows in memory before\n", "// exporting. Either that or export as multiple CSV sheets with max n rows each\n", "const MAX_EXPORT_ROW_COUNT = 500000\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 13 }
{ "scripts": { "start": "snowpack dev --polyfill-node", "build": "snowpack build --polyfill-node", "test": "NODE_ENV=test DEBUG= jest", "test:cy": "NODE_ENV=test cypress run", "test:interactive": "NODE_ENV=test cypress open --project .", "2020-test": "NODE_ENV=test DEBUG= node --experimental-vm-modules node_modules/jest/bin/jest.js --no-cache -b", "format": "prettier --write '{public,src}/**/*.{css,html,js,svelte}'" }, "dependencies": { "@supabase/supabase-js": "^1.0.2", "tailwindcss": "^1.4.6" }, "devDependencies": { "@rollup/plugin-json": "^4.1.0", "@rollup/plugin-run": "^2.0.2", "@snowpack/app-scripts-svelte": "^1.2.0", "@snowpack/plugin-dotenv": "^2.0.2", "@testing-library/cypress": "^7.0.1", "@testing-library/jest-dom": "^5.5.0", "@testing-library/svelte": "^3.0.0", "@vinicius73/rollup-plugin-skypack-resolver": "^2.1.0", "autoprefixer": "^9.8.0", "cypress": "^5.3.0", "cypress-svelte-unit-test": "^3.3.1", "husky": "^4.2.5", "jest": "^25.4.0", "lint-staged": "^10.2.10", "postcss": "^8.2.13", "postcss-cli": "^7.1.1", "postcss-load-config": "^2.1.0", "prettier": "2.0.5", "prettier-plugin-svelte": "^1.4.0", "rollup-plugin-inject-process-env": "^1.3.0", "snowpack": "^2.5.0", "svelte": "^3.21.0", "svelte-jester": "^1.1.5", "svelte-preprocess": "^3.9.7" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] } }
examples/todo-list/sveltejs-todo-list/package.json
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00017410251894034445, 0.00017196893168147653, 0.00017012316675391048, 0.00017176804249174893, 0.0000014304912383522606 ]
{ "id": 1, "code_window": [ "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n", "import { Sort, Filter } from 'components/grid/types'\n", "import { exportRowsToCsv } from 'components/grid/utils'\n", "import { useDispatch, useTrackedState } from 'components/grid/store'\n", "\n", "interface HeaderProps {\n", " sorts: Sort[]\n", " filters: Filter[]\n", " onAddColumn?: () => void\n", " onAddRow?: () => void\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// [Joshen] CSV exports require this guard as a fail-safe if the table is\n", "// just too large for a browser to keep all the rows in memory before\n", "// exporting. Either that or export as multiple CSV sheets with max n rows each\n", "const MAX_EXPORT_ROW_COUNT = 500000\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 13 }
--- id: auth-google-oauth title: 'Part Five: Google Oauth' description: 'Supabase Deep Dive Part 5: Google OAuth Provider' --- ### About How to add Google OAuth Logins to your Supabase Application. ### Watch <iframe className="w-full video-with-border" width="640" height="385" src="https://www.youtube-nocookie.com/embed/_XM9ziOzWk4" frameBorder="1" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowFullScreen></iframe> ### Logging in with external OAuth providers Connecting social logins such as Google, GitHub, or Facebook couldn't be easier. In this guide we'll walk you through the process of connecting Google, but the process is basically the same for all of the providers which includes: azure, bitbucket, github, gitlab, facebook, and google. First you'll need to create a google project inside their [cloud console](https://console.cloud.google.com/home/dashboard), in other providers they may refer to this as an "app" and is usually available on the company's developer portal. ![Create a new Google Project inside cloud console](/img/auth-5-1.png) Once you have a project, type "OAuth" into the search bar and open up "OAuth Consent Screen" ![Open the OAuth consent screen](/img/auth-5-2.png) Select 'External' and proceed to fill out the rest of the form fields ![Select External on the OAuth form](/img/auth-5-3.png) Next open up Credentials page on the left ![Open up Credentials page](/img/auth-5-4.png) And click to create a new set of credentials, select OAuth client ID as the option ![Create new oauth client id credentials](/img/auth-5-5.png) Now choose Web Application (assuming you're creating a web app) and in the Authorized redirect URI section you need to add: `https://<your-ref>.supabase.co/auth/v1/callback`. You can find your Supabase URL in Settings > API inside the Supabase dashboard. ![Add your redirect URI](/img/auth-5-6.png) Now you can grab the client ID and secret from the popup, and insert them into the google section inside the Supabase dashboard in Auth > Settings: ![take client id and secret](/img/auth-5-7.png) ![insert client id and secret into supabase dashboard in auth > auth](/img/auth-5-8.png) Hit save. Now you should be able to navigate in the browser to: ``` https://<your-ref>.supabase.co/auth/v1/authorize?provider=google ``` And log in to your service using any google or gmail account. You can additionally add a query parameter `redirect_to=` to the end of the URL for example: ``` https://<your-ref>.supabase.co/auth/v1/authorize?provider=google&redirect_to=http://localhost:3000/welcome ``` But make sure any URL you enter here is on the same host as the site url that you have entered on the Auth > Settings page on the Supabase dashboard. (There is additional functionality coming soon, where you'll be able to add additional URLs to the allow list). If you want to redirect the user to a specific page in your website or app after a successful authentication. You also have the option of requesting additional scopes from the oauth provider. Let's say for example you want the ability to send emails on behalf of the user's gmail account. You can do this by adding the query parameter `scopes`, like: ``` https://<your-ref>.supabase.co/auth/v1/authorize?provider=google&https://www.googleapis.com/auth/gmail.send ``` Note however that your app will usually have to be verified by Google before you can request advanced scopes such as this. The only thing left to implement is the UI, but if you prefer to use something pre-built, we have a handy [Auth Widget](https://github.com/supabase/ui/#using-supabase-ui-auth), where you can enable/disable whichever auth providers you want to support. For any support please get in touch at beta at [supabase.com](https://supabase.com) or for feature requests open an issue in the [backend](https://github.com/supabase/gotrue) or [frontend](https://github.com/supabase/gotrue-js) repos. ### Resources - [JWT debugger](https://jwt.io) ### Next steps - Watch [Part One: JWTs](/docs/learn/auth-deep-dive/auth-deep-dive-jwts) - Watch [Part Two: Row Level Security](/docs/learn/auth-deep-dive/auth-row-level-security) - Watch [Part Three: Policies](/docs/learn/auth-deep-dive/auth-policies) - Watch [Part Four: GoTrue](/docs/learn/auth-deep-dive/auth-gotrue) <!-- - Watch [Part Five: Google Oauth](/docs/learn/auth-deep-dive/auth-google-oauth) --> - Sign up for Supabase: [app.supabase.com](https://app.supabase.com)
web/docs/learn/auth-deep-dive/google-oauth.md
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00017967763415072113, 0.0001688650663709268, 0.00016133091412484646, 0.00016942061483860016, 0.000004479405561141903 ]
{ "id": 1, "code_window": [ "import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal'\n", "import { Sort, Filter } from 'components/grid/types'\n", "import { exportRowsToCsv } from 'components/grid/utils'\n", "import { useDispatch, useTrackedState } from 'components/grid/store'\n", "\n", "interface HeaderProps {\n", " sorts: Sort[]\n", " filters: Filter[]\n", " onAddColumn?: () => void\n", " onAddRow?: () => void\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "// [Joshen] CSV exports require this guard as a fail-safe if the table is\n", "// just too large for a browser to keep all the rows in memory before\n", "// exporting. Either that or export as multiple CSV sheets with max n rows each\n", "const MAX_EXPORT_ROW_COUNT = 500000\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 13 }
export const environment = { production: true, supabaseUrl: 'YOUR_SUPABASE_URL', supabaseKey: 'YOUR_SUPABASE_KEY', }
examples/todo-list/angular-todo-list/src/environments/environment.prod.ts
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00016370585944969207, 0.00016370585944969207, 0.00016370585944969207, 0.00016370585944969207, 0 ]
{ "id": 2, "code_window": [ " filters: Filter[]\n", "}\n", "const RowHeader: FC<RowHeaderProps> = ({ sorts, filters }) => {\n", " const state = useTrackedState()\n", " const dispatch = useDispatch()\n", "\n", " const [isExporting, setIsExporting] = useState(false)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { ui } = useStore()\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 92 }
import { IRowService } from '.' import { Filter, ServiceError, Sort, SupaRow, SupaTable } from '../../types' import { ERROR_PRIMARY_KEY_NOTFOUND, SupabaseGridQueue } from '../../constants' import Query from '../../query' import { isNumericalColumn } from '../../utils' import { useDispatch } from 'components/grid/store' export class SqlRowService implements IRowService { protected query = new Query() protected dispatch = useDispatch() constructor( protected table: SupaTable, protected onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>, protected onError: (error: any) => void ) {} async count(filters: Filter[]) { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).count() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) const query = queryChains.toSql() const { data, error } = await this.onSqlQuery(query) if (error) { return { error } } else { if (data?.length == 1) { return { data: data[0].count } } else { return { error: { message: 'fetch rows count failed' } } } } } async create(row: SupaRow) { return { error: { message: 'not implemented' } } } delete(rows: SupaRow[]) { const { primaryKeys, error } = this.getPrimaryKeys() if (error) return { error } let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).delete() primaryKeys!.forEach((key) => { const primaryKeyValues = rows.map((x) => x[key]) queryChains = queryChains.filter(key, 'in', primaryKeyValues) }) const query = queryChains.toSql() SupabaseGridQueue.add(async () => { const { error } = await this.onSqlQuery(query) if (error) throw error }).catch((error) => { this.onError(error) }) return {} } // For deleting all rows based on a given filter async deleteAll(filters: Filter[]) { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).delete() filters .filter((x) => x.value && x.value !== '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) const query = queryChains.toSql() return await this.onSqlQuery(query) } // For deleting all rows without any filter (clear entire table) async truncate() { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).truncate() const query = queryChains.toSql() return await this.onSqlQuery(query) } async fetchPage(page: number, rowsPerPage: number, filters: Filter[], sorts: Sort[]) { const pageFromZero = page > 0 ? page - 1 : page const from = pageFromZero * rowsPerPage const to = (pageFromZero + 1) * rowsPerPage - 1 let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) sorts.forEach((x) => { queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst) }) const query = queryChains.range(from, to).toSql() const { data, error } = await this.onSqlQuery(query) if (error) { this.onError(error) return { data: { rows: [] } } } else { const rows = data?.map((x: any, index: number) => { return { idx: index, ...x } as SupaRow }) return { data: { rows } } } } async fetchAllData(filters: Filter[], sorts: Sort[]) { // Paginate the request for very large tables to prevent stalling of API // [TODO] Note we probably still need a fail-safe if the table is just // too large for a browser to keep all the rows in memory before exporting // Either that or export as multiple CSV sheets, max n rows const rows: any[] = [] let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) sorts.forEach((x) => { queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst) }) // Starting from page 0, fetch 500 records per call let page = -1 let from = 0 let to = 0 let pageData = [] const rowsPerPage = 500 await (async () => { do { page += 1 from = page * rowsPerPage to = (page + 1) * rowsPerPage - 1 const query = queryChains.range(from, to).toSql() const { data, error } = await this.onSqlQuery(query) if (error) { this.onError(error) return { data: { rows: [] } } } else { rows.push(...data) pageData = data } } while (pageData.length === rowsPerPage) })() return rows } update(row: SupaRow, changedColumn?: string, onRowUpdate?: (value: any) => void) { const { primaryKeys, error } = this.getPrimaryKeys() if (error) { return { error } } const { idx, ...value } = row const matchValues: any = {} primaryKeys!.forEach((key) => { matchValues[key] = row[key] // fix: https://github.com/supabase/grid/issues/94 // remove primary key from updated value object delete value[key] }) const query = this.query .from(this.table.name, this.table.schema ?? undefined) .update( changedColumn ? { [changedColumn]: value[changedColumn], } : value, { returning: true } ) .match(matchValues) .toSql() SupabaseGridQueue.add(async () => { const { data, error } = await this.onSqlQuery(query) if (error) throw error if (onRowUpdate) onRowUpdate({ row: data[0], idx }) }).catch((error) => { this.onError(error) }) return {} } getPrimaryKeys(): { primaryKeys?: string[]; error?: ServiceError } { const pkColumns = this.table.columns.filter((x) => x.isPrimaryKey) if (!pkColumns || pkColumns.length == 0) { return { error: { message: ERROR_PRIMARY_KEY_NOTFOUND } } } return { primaryKeys: pkColumns.map((x) => x.name) } } /** * temporary fix until we impliment a better filter UI * which validate input value base on the column type */ formatFilterValue(filter: Filter) { const column = this.table.columns.find((x) => x.name == filter.column) if (column && isNumericalColumn(column.format)) { const numberValue = Number(filter.value) if (Number.isNaN(numberValue)) return filter.value else return Number(filter.value) } return filter.value } }
studio/components/grid/services/row/SqlRowService.ts
1
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.9278964400291443, 0.07220789790153503, 0.00016548069834243506, 0.00018547510262578726, 0.20351998507976532 ]
{ "id": 2, "code_window": [ " filters: Filter[]\n", "}\n", "const RowHeader: FC<RowHeaderProps> = ({ sorts, filters }) => {\n", " const state = useTrackedState()\n", " const dispatch = useDispatch()\n", "\n", " const [isExporting, setIsExporting] = useState(false)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { ui } = useStore()\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 92 }
import React from 'react' import Main from '.' import '../styles/tailwind.css' const Index = () => { return <Main /> } export default Index
apps/temp-community-tutorials/src/pages/_app.tsx
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0001769598020473495, 0.0001769598020473495, 0.0001769598020473495, 0.0001769598020473495, 0 ]
{ "id": 2, "code_window": [ " filters: Filter[]\n", "}\n", "const RowHeader: FC<RowHeaderProps> = ({ sorts, filters }) => {\n", " const state = useTrackedState()\n", " const dispatch = useDispatch()\n", "\n", " const [isExporting, setIsExporting] = useState(false)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { ui } = useStore()\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 92 }
// https://github.com/dmfilipenko/timezones.json/blob/master/timezones.json export const ALL_TIMEZONES = [ { value: 'Dateline Standard Time', abbr: 'DST', offset: -12, isdst: false, text: '(UTC-12:00) International Date Line West', utc: ['Etc/GMT+12'], }, { value: 'UTC-11', abbr: 'U', offset: -11, isdst: false, text: '(UTC-11:00) Coordinated Universal Time-11', utc: ['Etc/GMT+11', 'Pacific/Midway', 'Pacific/Niue', 'Pacific/Pago_Pago'], }, { value: 'Hawaiian Standard Time', abbr: 'HST', offset: -10, isdst: false, text: '(UTC-10:00) Hawaii', utc: [ 'Etc/GMT+10', 'Pacific/Honolulu', 'Pacific/Johnston', 'Pacific/Rarotonga', 'Pacific/Tahiti', ], }, { value: 'Alaskan Standard Time', abbr: 'AKDT', offset: -8, isdst: true, text: '(UTC-09:00) Alaska', utc: [ 'America/Anchorage', 'America/Juneau', 'America/Nome', 'America/Sitka', 'America/Yakutat', ], }, { value: 'Pacific Standard Time (Mexico)', abbr: 'PDT', offset: -7, isdst: true, text: '(UTC-08:00) Baja California', utc: ['America/Santa_Isabel'], }, { value: 'Pacific Daylight Time', abbr: 'PDT', offset: -7, isdst: true, text: '(UTC-07:00) Pacific Daylight Time (US & Canada)', utc: ['America/Los_Angeles', 'America/Tijuana', 'America/Vancouver'], }, { value: 'Pacific Standard Time', abbr: 'PST', offset: -8, isdst: false, text: '(UTC-08:00) Pacific Standard Time (US & Canada)', utc: ['America/Los_Angeles', 'America/Tijuana', 'America/Vancouver', 'PST8PDT'], }, { value: 'US Mountain Standard Time', abbr: 'UMST', offset: -7, isdst: false, text: '(UTC-07:00) Arizona', utc: [ 'America/Creston', 'America/Dawson', 'America/Dawson_Creek', 'America/Hermosillo', 'America/Phoenix', 'America/Whitehorse', 'Etc/GMT+7', ], }, { value: 'Mountain Standard Time (Mexico)', abbr: 'MDT', offset: -6, isdst: true, text: '(UTC-07:00) Chihuahua, La Paz, Mazatlan', utc: ['America/Chihuahua', 'America/Mazatlan'], }, { value: 'Mountain Standard Time', abbr: 'MDT', offset: -6, isdst: true, text: '(UTC-07:00) Mountain Time (US & Canada)', utc: [ 'America/Boise', 'America/Cambridge_Bay', 'America/Denver', 'America/Edmonton', 'America/Inuvik', 'America/Ojinaga', 'America/Yellowknife', 'MST7MDT', ], }, { value: 'Central America Standard Time', abbr: 'CAST', offset: -6, isdst: false, text: '(UTC-06:00) Central America', utc: [ 'America/Belize', 'America/Costa_Rica', 'America/El_Salvador', 'America/Guatemala', 'America/Managua', 'America/Tegucigalpa', 'Etc/GMT+6', 'Pacific/Galapagos', ], }, { value: 'Central Standard Time', abbr: 'CDT', offset: -5, isdst: true, text: '(UTC-06:00) Central Time (US & Canada)', utc: [ 'America/Chicago', 'America/Indiana/Knox', 'America/Indiana/Tell_City', 'America/Matamoros', 'America/Menominee', 'America/North_Dakota/Beulah', 'America/North_Dakota/Center', 'America/North_Dakota/New_Salem', 'America/Rainy_River', 'America/Rankin_Inlet', 'America/Resolute', 'America/Winnipeg', 'CST6CDT', ], }, { value: 'Central Standard Time (Mexico)', abbr: 'CDT', offset: -5, isdst: true, text: '(UTC-06:00) Guadalajara, Mexico City, Monterrey', utc: [ 'America/Bahia_Banderas', 'America/Cancun', 'America/Merida', 'America/Mexico_City', 'America/Monterrey', ], }, { value: 'Canada Central Standard Time', abbr: 'CCST', offset: -6, isdst: false, text: '(UTC-06:00) Saskatchewan', utc: ['America/Regina', 'America/Swift_Current'], }, { value: 'SA Pacific Standard Time', abbr: 'SPST', offset: -5, isdst: false, text: '(UTC-05:00) Bogota, Lima, Quito', utc: [ 'America/Bogota', 'America/Cayman', 'America/Coral_Harbour', 'America/Eirunepe', 'America/Guayaquil', 'America/Jamaica', 'America/Lima', 'America/Panama', 'America/Rio_Branco', 'Etc/GMT+5', ], }, { value: 'Eastern Standard Time', abbr: 'EST', offset: -5, isdst: false, text: '(UTC-05:00) Eastern Time (US & Canada)', utc: [ 'America/Detroit', 'America/Havana', 'America/Indiana/Petersburg', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Iqaluit', 'America/Kentucky/Monticello', 'America/Louisville', 'America/Montreal', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Pangnirtung', 'America/Port-au-Prince', 'America/Thunder_Bay', 'America/Toronto', ], }, { value: 'Eastern Daylight Time', abbr: 'EDT', offset: -4, isdst: true, text: '(UTC-04:00) Eastern Daylight Time (US & Canada)', utc: [ 'America/Detroit', 'America/Havana', 'America/Indiana/Petersburg', 'America/Indiana/Vincennes', 'America/Indiana/Winamac', 'America/Iqaluit', 'America/Kentucky/Monticello', 'America/Louisville', 'America/Montreal', 'America/Nassau', 'America/New_York', 'America/Nipigon', 'America/Pangnirtung', 'America/Port-au-Prince', 'America/Thunder_Bay', 'America/Toronto', ], }, { value: 'US Eastern Standard Time', abbr: 'UEDT', offset: -5, isdst: false, text: '(UTC-05:00) Indiana (East)', utc: ['America/Indiana/Marengo', 'America/Indiana/Vevay', 'America/Indianapolis'], }, { value: 'Venezuela Standard Time', abbr: 'VST', offset: -4.5, isdst: false, text: '(UTC-04:30) Caracas', utc: ['America/Caracas'], }, { value: 'Paraguay Standard Time', abbr: 'PYT', offset: -4, isdst: false, text: '(UTC-04:00) Asuncion', utc: ['America/Asuncion'], }, { value: 'Atlantic Standard Time', abbr: 'ADT', offset: -3, isdst: true, text: '(UTC-04:00) Atlantic Time (Canada)', utc: [ 'America/Glace_Bay', 'America/Goose_Bay', 'America/Halifax', 'America/Moncton', 'America/Thule', 'Atlantic/Bermuda', ], }, { value: 'Central Brazilian Standard Time', abbr: 'CBST', offset: -4, isdst: false, text: '(UTC-04:00) Cuiaba', utc: ['America/Campo_Grande', 'America/Cuiaba'], }, { value: 'SA Western Standard Time', abbr: 'SWST', offset: -4, isdst: false, text: '(UTC-04:00) Georgetown, La Paz, Manaus, San Juan', utc: [ 'America/Anguilla', 'America/Antigua', 'America/Aruba', 'America/Barbados', 'America/Blanc-Sablon', 'America/Boa_Vista', 'America/Curacao', 'America/Dominica', 'America/Grand_Turk', 'America/Grenada', 'America/Guadeloupe', 'America/Guyana', 'America/Kralendijk', 'America/La_Paz', 'America/Lower_Princes', 'America/Manaus', 'America/Marigot', 'America/Martinique', 'America/Montserrat', 'America/Port_of_Spain', 'America/Porto_Velho', 'America/Puerto_Rico', 'America/Santo_Domingo', 'America/St_Barthelemy', 'America/St_Kitts', 'America/St_Lucia', 'America/St_Thomas', 'America/St_Vincent', 'America/Tortola', 'Etc/GMT+4', ], }, { value: 'Pacific SA Standard Time', abbr: 'PSST', offset: -4, isdst: false, text: '(UTC-04:00) Santiago', utc: ['America/Santiago', 'Antarctica/Palmer'], }, { value: 'Newfoundland Standard Time', abbr: 'NDT', offset: -2.5, isdst: true, text: '(UTC-03:30) Newfoundland', utc: ['America/St_Johns'], }, { value: 'E. South America Standard Time', abbr: 'ESAST', offset: -3, isdst: false, text: '(UTC-03:00) Brasilia', utc: ['America/Sao_Paulo'], }, { value: 'Argentina Standard Time', abbr: 'AST', offset: -3, isdst: false, text: '(UTC-03:00) Buenos Aires', utc: [ 'America/Argentina/La_Rioja', 'America/Argentina/Rio_Gallegos', 'America/Argentina/Salta', 'America/Argentina/San_Juan', 'America/Argentina/San_Luis', 'America/Argentina/Tucuman', 'America/Argentina/Ushuaia', 'America/Buenos_Aires', 'America/Catamarca', 'America/Cordoba', 'America/Jujuy', 'America/Mendoza', ], }, { value: 'SA Eastern Standard Time', abbr: 'SEST', offset: -3, isdst: false, text: '(UTC-03:00) Cayenne, Fortaleza', utc: [ 'America/Araguaina', 'America/Belem', 'America/Cayenne', 'America/Fortaleza', 'America/Maceio', 'America/Paramaribo', 'America/Recife', 'America/Santarem', 'Antarctica/Rothera', 'Atlantic/Stanley', 'Etc/GMT+3', ], }, { value: 'Greenland Standard Time', abbr: 'GDT', offset: -3, isdst: true, text: '(UTC-03:00) Greenland', utc: ['America/Godthab'], }, { value: 'Montevideo Standard Time', abbr: 'MST', offset: -3, isdst: false, text: '(UTC-03:00) Montevideo', utc: ['America/Montevideo'], }, { value: 'Bahia Standard Time', abbr: 'BST', offset: -3, isdst: false, text: '(UTC-03:00) Salvador', utc: ['America/Bahia'], }, { value: 'UTC-02', abbr: 'U', offset: -2, isdst: false, text: '(UTC-02:00) Coordinated Universal Time-02', utc: ['America/Noronha', 'Atlantic/South_Georgia', 'Etc/GMT+2'], }, { value: 'Mid-Atlantic Standard Time', abbr: 'MDT', offset: -1, isdst: true, text: '(UTC-02:00) Mid-Atlantic - Old', utc: [], }, { value: 'Azores Standard Time', abbr: 'ADT', offset: 0, isdst: true, text: '(UTC-01:00) Azores', utc: ['America/Scoresbysund', 'Atlantic/Azores'], }, { value: 'Cape Verde Standard Time', abbr: 'CVST', offset: -1, isdst: false, text: '(UTC-01:00) Cape Verde Is.', utc: ['Atlantic/Cape_Verde', 'Etc/GMT+1'], }, { value: 'Morocco Standard Time', abbr: 'MDT', offset: 1, isdst: true, text: '(UTC) Casablanca', utc: ['Africa/Casablanca', 'Africa/El_Aaiun'], }, { value: 'UTC', abbr: 'UTC', offset: 0, isdst: false, text: '(UTC) Coordinated Universal Time', utc: ['America/Danmarkshavn', 'Etc/GMT'], }, { value: 'GMT Standard Time', abbr: 'GMT', offset: 0, isdst: false, text: '(UTC) Edinburgh, London', utc: ['Europe/Isle_of_Man', 'Europe/Guernsey', 'Europe/Jersey', 'Europe/London'], }, { value: 'British Summer Time', abbr: 'BST', offset: 1, isdst: true, text: '(UTC+01:00) Edinburgh, London', utc: ['Europe/Isle_of_Man', 'Europe/Guernsey', 'Europe/Jersey', 'Europe/London'], }, { value: 'GMT Standard Time', abbr: 'GDT', offset: 1, isdst: true, text: '(UTC) Dublin, Lisbon', utc: [ 'Atlantic/Canary', 'Atlantic/Faeroe', 'Atlantic/Madeira', 'Europe/Dublin', 'Europe/Lisbon', ], }, { value: 'Greenwich Standard Time', abbr: 'GST', offset: 0, isdst: false, text: '(UTC) Monrovia, Reykjavik', utc: [ 'Africa/Abidjan', 'Africa/Accra', 'Africa/Bamako', 'Africa/Banjul', 'Africa/Bissau', 'Africa/Conakry', 'Africa/Dakar', 'Africa/Freetown', 'Africa/Lome', 'Africa/Monrovia', 'Africa/Nouakchott', 'Africa/Ouagadougou', 'Africa/Sao_Tome', 'Atlantic/Reykjavik', 'Atlantic/St_Helena', ], }, { value: 'W. Europe Standard Time', abbr: 'WEDT', offset: 2, isdst: true, text: '(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna', utc: [ 'Arctic/Longyearbyen', 'Europe/Amsterdam', 'Europe/Andorra', 'Europe/Berlin', 'Europe/Busingen', 'Europe/Gibraltar', 'Europe/Luxembourg', 'Europe/Malta', 'Europe/Monaco', 'Europe/Oslo', 'Europe/Rome', 'Europe/San_Marino', 'Europe/Stockholm', 'Europe/Vaduz', 'Europe/Vatican', 'Europe/Vienna', 'Europe/Zurich', ], }, { value: 'Central Europe Standard Time', abbr: 'CEDT', offset: 2, isdst: true, text: '(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague', utc: [ 'Europe/Belgrade', 'Europe/Bratislava', 'Europe/Budapest', 'Europe/Ljubljana', 'Europe/Podgorica', 'Europe/Prague', 'Europe/Tirane', ], }, { value: 'Romance Standard Time', abbr: 'RDT', offset: 2, isdst: true, text: '(UTC+01:00) Brussels, Copenhagen, Madrid, Paris', utc: ['Africa/Ceuta', 'Europe/Brussels', 'Europe/Copenhagen', 'Europe/Madrid', 'Europe/Paris'], }, { value: 'Central European Standard Time', abbr: 'CEDT', offset: 2, isdst: true, text: '(UTC+01:00) Sarajevo, Skopje, Warsaw, Zagreb', utc: ['Europe/Sarajevo', 'Europe/Skopje', 'Europe/Warsaw', 'Europe/Zagreb'], }, { value: 'W. Central Africa Standard Time', abbr: 'WCAST', offset: 1, isdst: false, text: '(UTC+01:00) West Central Africa', utc: [ 'Africa/Algiers', 'Africa/Bangui', 'Africa/Brazzaville', 'Africa/Douala', 'Africa/Kinshasa', 'Africa/Lagos', 'Africa/Libreville', 'Africa/Luanda', 'Africa/Malabo', 'Africa/Ndjamena', 'Africa/Niamey', 'Africa/Porto-Novo', 'Africa/Tunis', 'Etc/GMT-1', ], }, { value: 'Namibia Standard Time', abbr: 'NST', offset: 1, isdst: false, text: '(UTC+01:00) Windhoek', utc: ['Africa/Windhoek'], }, { value: 'GTB Standard Time', abbr: 'GDT', offset: 3, isdst: true, text: '(UTC+02:00) Athens, Bucharest', utc: ['Asia/Nicosia', 'Europe/Athens', 'Europe/Bucharest', 'Europe/Chisinau'], }, { value: 'Middle East Standard Time', abbr: 'MEDT', offset: 3, isdst: true, text: '(UTC+02:00) Beirut', utc: ['Asia/Beirut'], }, { value: 'Egypt Standard Time', abbr: 'EST', offset: 2, isdst: false, text: '(UTC+02:00) Cairo', utc: ['Africa/Cairo'], }, { value: 'Syria Standard Time', abbr: 'SDT', offset: 3, isdst: true, text: '(UTC+02:00) Damascus', utc: ['Asia/Damascus'], }, { value: 'E. Europe Standard Time', abbr: 'EEDT', offset: 3, isdst: true, text: '(UTC+02:00) E. Europe', utc: [ 'Asia/Nicosia', 'Europe/Athens', 'Europe/Bucharest', 'Europe/Chisinau', 'Europe/Helsinki', 'Europe/Kiev', 'Europe/Mariehamn', 'Europe/Nicosia', 'Europe/Riga', 'Europe/Sofia', 'Europe/Tallinn', 'Europe/Uzhgorod', 'Europe/Vilnius', 'Europe/Zaporozhye', ], }, { value: 'South Africa Standard Time', abbr: 'SAST', offset: 2, isdst: false, text: '(UTC+02:00) Harare, Pretoria', utc: [ 'Africa/Blantyre', 'Africa/Bujumbura', 'Africa/Gaborone', 'Africa/Harare', 'Africa/Johannesburg', 'Africa/Kigali', 'Africa/Lubumbashi', 'Africa/Lusaka', 'Africa/Maputo', 'Africa/Maseru', 'Africa/Mbabane', 'Etc/GMT-2', ], }, { value: 'FLE Standard Time', abbr: 'FDT', offset: 3, isdst: true, text: '(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius', utc: [ 'Europe/Helsinki', 'Europe/Kiev', 'Europe/Mariehamn', 'Europe/Riga', 'Europe/Sofia', 'Europe/Tallinn', 'Europe/Uzhgorod', 'Europe/Vilnius', 'Europe/Zaporozhye', ], }, { value: 'Turkey Standard Time', abbr: 'TDT', offset: 3, isdst: false, text: '(UTC+03:00) Istanbul', utc: ['Europe/Istanbul'], }, { value: 'Israel Standard Time', abbr: 'JDT', offset: 3, isdst: true, text: '(UTC+02:00) Jerusalem', utc: ['Asia/Jerusalem'], }, { value: 'Libya Standard Time', abbr: 'LST', offset: 2, isdst: false, text: '(UTC+02:00) Tripoli', utc: ['Africa/Tripoli'], }, { value: 'Jordan Standard Time', abbr: 'JST', offset: 3, isdst: false, text: '(UTC+03:00) Amman', utc: ['Asia/Amman'], }, { value: 'Arabic Standard Time', abbr: 'AST', offset: 3, isdst: false, text: '(UTC+03:00) Baghdad', utc: ['Asia/Baghdad'], }, { value: 'Kaliningrad Standard Time', abbr: 'KST', offset: 3, isdst: false, text: '(UTC+02:00) Kaliningrad', utc: ['Europe/Kaliningrad'], }, { value: 'Arab Standard Time', abbr: 'AST', offset: 3, isdst: false, text: '(UTC+03:00) Kuwait, Riyadh', utc: ['Asia/Aden', 'Asia/Bahrain', 'Asia/Kuwait', 'Asia/Qatar', 'Asia/Riyadh'], }, { value: 'E. Africa Standard Time', abbr: 'EAST', offset: 3, isdst: false, text: '(UTC+03:00) Nairobi', utc: [ 'Africa/Addis_Ababa', 'Africa/Asmera', 'Africa/Dar_es_Salaam', 'Africa/Djibouti', 'Africa/Juba', 'Africa/Kampala', 'Africa/Khartoum', 'Africa/Mogadishu', 'Africa/Nairobi', 'Antarctica/Syowa', 'Etc/GMT-3', 'Indian/Antananarivo', 'Indian/Comoro', 'Indian/Mayotte', ], }, { value: 'Moscow Standard Time', abbr: 'MSK', offset: 3, isdst: false, text: '(UTC+03:00) Moscow, St. Petersburg, Volgograd, Minsk', utc: ['Europe/Kirov', 'Europe/Moscow', 'Europe/Simferopol', 'Europe/Volgograd', 'Europe/Minsk'], }, { value: 'Samara Time', abbr: 'SAMT', offset: 4, isdst: false, text: '(UTC+04:00) Samara, Ulyanovsk, Saratov', utc: ['Europe/Astrakhan', 'Europe/Samara', 'Europe/Ulyanovsk'], }, { value: 'Iran Standard Time', abbr: 'IDT', offset: 4.5, isdst: true, text: '(UTC+03:30) Tehran', utc: ['Asia/Tehran'], }, { value: 'Arabian Standard Time', abbr: 'AST', offset: 4, isdst: false, text: '(UTC+04:00) Abu Dhabi, Muscat', utc: ['Asia/Dubai', 'Asia/Muscat', 'Etc/GMT-4'], }, { value: 'Azerbaijan Standard Time', abbr: 'ADT', offset: 5, isdst: true, text: '(UTC+04:00) Baku', utc: ['Asia/Baku'], }, { value: 'Mauritius Standard Time', abbr: 'MST', offset: 4, isdst: false, text: '(UTC+04:00) Port Louis', utc: ['Indian/Mahe', 'Indian/Mauritius', 'Indian/Reunion'], }, { value: 'Georgian Standard Time', abbr: 'GET', offset: 4, isdst: false, text: '(UTC+04:00) Tbilisi', utc: ['Asia/Tbilisi'], }, { value: 'Caucasus Standard Time', abbr: 'CST', offset: 4, isdst: false, text: '(UTC+04:00) Yerevan', utc: ['Asia/Yerevan'], }, { value: 'Afghanistan Standard Time', abbr: 'AST', offset: 4.5, isdst: false, text: '(UTC+04:30) Kabul', utc: ['Asia/Kabul'], }, { value: 'West Asia Standard Time', abbr: 'WAST', offset: 5, isdst: false, text: '(UTC+05:00) Ashgabat, Tashkent', utc: [ 'Antarctica/Mawson', 'Asia/Aqtau', 'Asia/Aqtobe', 'Asia/Ashgabat', 'Asia/Dushanbe', 'Asia/Oral', 'Asia/Samarkand', 'Asia/Tashkent', 'Etc/GMT-5', 'Indian/Kerguelen', 'Indian/Maldives', ], }, { value: 'Yekaterinburg Time', abbr: 'YEKT', offset: 5, isdst: false, text: '(UTC+05:00) Yekaterinburg', utc: ['Asia/Yekaterinburg'], }, { value: 'Pakistan Standard Time', abbr: 'PKT', offset: 5, isdst: false, text: '(UTC+05:00) Islamabad, Karachi', utc: ['Asia/Karachi'], }, { value: 'India Standard Time', abbr: 'IST', offset: 5.5, isdst: false, text: '(UTC+05:30) Chennai, Kolkata, Mumbai, New Delhi', utc: ['Asia/Kolkata', 'Asia/Calcutta'], }, { value: 'Sri Lanka Standard Time', abbr: 'SLST', offset: 5.5, isdst: false, text: '(UTC+05:30) Sri Jayawardenepura', utc: ['Asia/Colombo'], }, { value: 'Nepal Standard Time', abbr: 'NST', offset: 5.75, isdst: false, text: '(UTC+05:45) Kathmandu', utc: ['Asia/Kathmandu'], }, { value: 'Central Asia Standard Time', abbr: 'CAST', offset: 6, isdst: false, text: '(UTC+06:00) Nur-Sultan (Astana)', utc: [ 'Antarctica/Vostok', 'Asia/Almaty', 'Asia/Bishkek', 'Asia/Qyzylorda', 'Asia/Urumqi', 'Etc/GMT-6', 'Indian/Chagos', ], }, { value: 'Bangladesh Standard Time', abbr: 'BST', offset: 6, isdst: false, text: '(UTC+06:00) Dhaka', utc: ['Asia/Dhaka', 'Asia/Thimphu'], }, { value: 'Myanmar Standard Time', abbr: 'MST', offset: 6.5, isdst: false, text: '(UTC+06:30) Yangon (Rangoon)', utc: ['Asia/Rangoon', 'Indian/Cocos'], }, { value: 'SE Asia Standard Time', abbr: 'SAST', offset: 7, isdst: false, text: '(UTC+07:00) Bangkok, Hanoi, Jakarta', utc: [ 'Antarctica/Davis', 'Asia/Bangkok', 'Asia/Hovd', 'Asia/Jakarta', 'Asia/Phnom_Penh', 'Asia/Pontianak', 'Asia/Saigon', 'Asia/Vientiane', 'Etc/GMT-7', 'Indian/Christmas', ], }, { value: 'N. Central Asia Standard Time', abbr: 'NCAST', offset: 7, isdst: false, text: '(UTC+07:00) Novosibirsk', utc: ['Asia/Novokuznetsk', 'Asia/Novosibirsk', 'Asia/Omsk'], }, { value: 'China Standard Time', abbr: 'CST', offset: 8, isdst: false, text: '(UTC+08:00) Beijing, Chongqing, Hong Kong, Urumqi', utc: ['Asia/Hong_Kong', 'Asia/Macau', 'Asia/Shanghai'], }, { value: 'North Asia Standard Time', abbr: 'NAST', offset: 8, isdst: false, text: '(UTC+08:00) Krasnoyarsk', utc: ['Asia/Krasnoyarsk'], }, { value: 'Singapore Standard Time', abbr: 'MPST', offset: 8, isdst: false, text: '(UTC+08:00) Kuala Lumpur, Singapore', utc: [ 'Asia/Brunei', 'Asia/Kuala_Lumpur', 'Asia/Kuching', 'Asia/Makassar', 'Asia/Manila', 'Asia/Singapore', 'Etc/GMT-8', ], }, { value: 'W. Australia Standard Time', abbr: 'WAST', offset: 8, isdst: false, text: '(UTC+08:00) Perth', utc: ['Antarctica/Casey', 'Australia/Perth'], }, { value: 'Taipei Standard Time', abbr: 'TST', offset: 8, isdst: false, text: '(UTC+08:00) Taipei', utc: ['Asia/Taipei'], }, { value: 'Ulaanbaatar Standard Time', abbr: 'UST', offset: 8, isdst: false, text: '(UTC+08:00) Ulaanbaatar', utc: ['Asia/Choibalsan', 'Asia/Ulaanbaatar'], }, { value: 'North Asia East Standard Time', abbr: 'NAEST', offset: 8, isdst: false, text: '(UTC+08:00) Irkutsk', utc: ['Asia/Irkutsk'], }, { value: 'Japan Standard Time', abbr: 'JST', offset: 9, isdst: false, text: '(UTC+09:00) Osaka, Sapporo, Tokyo', utc: ['Asia/Dili', 'Asia/Jayapura', 'Asia/Tokyo', 'Etc/GMT-9', 'Pacific/Palau'], }, { value: 'Korea Standard Time', abbr: 'KST', offset: 9, isdst: false, text: '(UTC+09:00) Seoul', utc: ['Asia/Pyongyang', 'Asia/Seoul'], }, { value: 'Cen. Australia Standard Time', abbr: 'CAST', offset: 9.5, isdst: false, text: '(UTC+09:30) Adelaide', utc: ['Australia/Adelaide', 'Australia/Broken_Hill'], }, { value: 'AUS Central Standard Time', abbr: 'ACST', offset: 9.5, isdst: false, text: '(UTC+09:30) Darwin', utc: ['Australia/Darwin'], }, { value: 'E. Australia Standard Time', abbr: 'EAST', offset: 10, isdst: false, text: '(UTC+10:00) Brisbane', utc: ['Australia/Brisbane', 'Australia/Lindeman'], }, { value: 'AUS Eastern Standard Time', abbr: 'AEST', offset: 10, isdst: false, text: '(UTC+10:00) Canberra, Melbourne, Sydney', utc: ['Australia/Melbourne', 'Australia/Sydney'], }, { value: 'West Pacific Standard Time', abbr: 'WPST', offset: 10, isdst: false, text: '(UTC+10:00) Guam, Port Moresby', utc: [ 'Antarctica/DumontDUrville', 'Etc/GMT-10', 'Pacific/Guam', 'Pacific/Port_Moresby', 'Pacific/Saipan', 'Pacific/Truk', ], }, { value: 'Tasmania Standard Time', abbr: 'TST', offset: 10, isdst: false, text: '(UTC+10:00) Hobart', utc: ['Australia/Currie', 'Australia/Hobart'], }, { value: 'Yakutsk Standard Time', abbr: 'YST', offset: 9, isdst: false, text: '(UTC+09:00) Yakutsk', utc: ['Asia/Chita', 'Asia/Khandyga', 'Asia/Yakutsk'], }, { value: 'Central Pacific Standard Time', abbr: 'CPST', offset: 11, isdst: false, text: '(UTC+11:00) Solomon Is., New Caledonia', utc: [ 'Antarctica/Macquarie', 'Etc/GMT-11', 'Pacific/Efate', 'Pacific/Guadalcanal', 'Pacific/Kosrae', 'Pacific/Noumea', 'Pacific/Ponape', ], }, { value: 'Vladivostok Standard Time', abbr: 'VST', offset: 11, isdst: false, text: '(UTC+11:00) Vladivostok', utc: ['Asia/Sakhalin', 'Asia/Ust-Nera', 'Asia/Vladivostok'], }, { value: 'New Zealand Standard Time', abbr: 'NZST', offset: 12, isdst: false, text: '(UTC+12:00) Auckland, Wellington', utc: ['Antarctica/McMurdo', 'Pacific/Auckland'], }, { value: 'UTC+12', abbr: 'U', offset: 12, isdst: false, text: '(UTC+12:00) Coordinated Universal Time+12', utc: [ 'Etc/GMT-12', 'Pacific/Funafuti', 'Pacific/Kwajalein', 'Pacific/Majuro', 'Pacific/Nauru', 'Pacific/Tarawa', 'Pacific/Wake', 'Pacific/Wallis', ], }, { value: 'Fiji Standard Time', abbr: 'FST', offset: 12, isdst: false, text: '(UTC+12:00) Fiji', utc: ['Pacific/Fiji'], }, { value: 'Magadan Standard Time', abbr: 'MST', offset: 12, isdst: false, text: '(UTC+12:00) Magadan', utc: ['Asia/Anadyr', 'Asia/Kamchatka', 'Asia/Magadan', 'Asia/Srednekolymsk'], }, { value: 'Kamchatka Standard Time', abbr: 'KDT', offset: 13, isdst: true, text: '(UTC+12:00) Petropavlovsk-Kamchatsky - Old', utc: ['Asia/Kamchatka'], }, { value: 'Tonga Standard Time', abbr: 'TST', offset: 13, isdst: false, text: "(UTC+13:00) Nuku'alofa", utc: ['Etc/GMT-13', 'Pacific/Enderbury', 'Pacific/Fakaofo', 'Pacific/Tongatapu'], }, { value: 'Samoa Standard Time', abbr: 'SST', offset: 13, isdst: false, text: '(UTC+13:00) Samoa', utc: ['Pacific/Apia'], }, ]
studio/components/interfaces/Database/Backups/PITRBackupSelection/PITRBackupSelection.constants.ts
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00019948398403357714, 0.0001746967463986948, 0.00017095459043048322, 0.00017437779752071947, 0.0000026474644982954487 ]
{ "id": 2, "code_window": [ " filters: Filter[]\n", "}\n", "const RowHeader: FC<RowHeaderProps> = ({ sorts, filters }) => {\n", " const state = useTrackedState()\n", " const dispatch = useDispatch()\n", "\n", " const [isExporting, setIsExporting] = useState(false)\n", "\n" ], "labels": [ "keep", "keep", "add", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " const { ui } = useStore()\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 92 }
import React, { useEffect, useState } from 'react' import { View, StyleSheet, SafeAreaView, FlatList } from 'react-native' import { Styles } from '../lib/constants' import { Text } from 'react-native-elements' import { supabase } from '../lib/initSupabase' import { useUser } from './UserContext' import { Button, Input, ListItem, CheckBox } from 'react-native-elements' /** URL polyfill. Required for Supabase queries to work in React Native. */ import 'react-native-url-polyfill/auto' type Todo = { id: number user_id: string task: string is_complete: boolean inserted_at: Date } export default function TodoList() { const { user } = useUser() const [todos, setTodos] = useState<Array<Todo>>([]) const [newTaskText, setNewTaskText] = useState<string>('') useEffect(() => { fetchTodos() }, []) const fetchTodos = async () => { const { data: todos, error } = await supabase .from<Todo>('todos') .select('*') .order('id', { ascending: false }) if (error) { console.log('error', error) } else { setTodos(todos!) } } const addTodo = async (taskText: string) => { const task = taskText.trim() console.log('newtask:', task) if (task.length) { const { data: todo, error } = await supabase .from<Todo>('todos') .insert({ task, user_id: user!.id }) .single() if (error) { console.log(error.message) } else { setTodos([todo!, ...todos]) setNewTaskText('') } } } const toggleCompleted = async (id: number, is_complete: boolean) => { const { data, error } = await supabase .from<Todo>('todos') .update({ is_complete: !is_complete }) .eq('id', id) .single() if (error) { console.log(error) } else { setTodos(todos.map((todo) => (todo.id === id ? data! : todo))) } } const deleteTodo = async (id: number) => { const { error } = await supabase.from<Todo>('todos').delete().eq('id', id) if (error) { console.log('error', error) } else { setTodos(todos.filter((x) => x.id !== Number(id))) } } return ( <View> <View style={[styles.verticallySpaced, { marginTop: 20 }]}> <Button title="Sign out" onPress={() => supabase.auth.signOut()} /> </View> <View style={[styles.verticallySpaced, { marginTop: 20 }]}> <Input label="New todo" leftIcon={{ type: 'font-awesome', name: 'tasks' }} onChangeText={(text) => setNewTaskText(text)} value={newTaskText} /> <Button title="Add" onPress={() => addTodo(newTaskText)} /> </View> <SafeAreaView style={styles.verticallySpaced}> <FlatList scrollEnabled={true} data={todos} keyExtractor={(item) => `${item.id}`} renderItem={({ item: todo }) => ( <ListItem bottomDivider> <ListItem.Content> <View style={[ { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', }, ]} > <CheckBox checked={todo.is_complete} onPress={() => toggleCompleted(todo.id, todo.is_complete)} /> <Text h3 style={{ margin: 'auto' }}> {todo.task} </Text> <Button title="Delete" onPress={() => deleteTodo(todo.id)} /> </View> </ListItem.Content> </ListItem> )} /> </SafeAreaView> </View> ) } const styles = StyleSheet.create({ container: { marginTop: 40, padding: Styles.spacing, }, verticallySpaced: { paddingTop: 4, paddingBottom: 4, alignSelf: 'stretch', }, })
examples/todo-list/react-native-ts-todo-list/native/components/TodoList.tsx
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0001783342013368383, 0.0001730968215269968, 0.0001686641771811992, 0.0001733798999339342, 0.000002819053179337061 ]
{ "id": 3, "code_window": [ " })\n", " }\n", "\n", " async function onRowsExportCSV() {\n", " setIsExporting(true)\n", " const rows = allRowsSelected\n", " ? await state.rowService!.fetchAllData(filters, sorts)\n", " : allRows.filter((x) => selectedRows.has(x.idx))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (allRowsSelected && totalRows > MAX_EXPORT_ROW_COUNT) {\n", " ui.setNotification({\n", " category: 'error',\n", " message: `Sorry! We're unable to support exporting of CSV for row counts larger than ${MAX_EXPORT_ROW_COUNT.toLocaleString()} at the moment.`,\n", " })\n", " return setIsExporting(false)\n", " }\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 145 }
import { FC, useState, ReactNode } from 'react' import { Button, IconDownload, IconPlus, IconX, IconTrash } from '@supabase/ui' import { saveAs } from 'file-saver' import FilterDropdown from './filter' import SortPopover from './sort' import StatusLabel from './StatusLabel' import RefreshButton from './RefreshButton' import { confirmAlert } from 'components/to-be-cleaned/ModalsDeprecated/ConfirmModal' import { Sort, Filter } from 'components/grid/types' import { exportRowsToCsv } from 'components/grid/utils' import { useDispatch, useTrackedState } from 'components/grid/store' interface HeaderProps { sorts: Sort[] filters: Filter[] onAddColumn?: () => void onAddRow?: () => void headerActions?: ReactNode } const Header: FC<HeaderProps> = ({ sorts, filters, onAddColumn, onAddRow, headerActions }) => { const state = useTrackedState() const { selectedRows } = state return ( <div className="bg-scale-100 dark:bg-scale-300 flex h-10 items-center justify-between px-5"> {selectedRows.size > 0 ? ( <RowHeader sorts={sorts} filters={filters} /> ) : ( <DefaultHeader sorts={sorts} filters={filters} onAddColumn={onAddColumn} onAddRow={onAddRow} /> )} <div className="sb-grid-header__inner"> {headerActions} <StatusLabel /> </div> </div> ) } export default Header interface DefaultHeaderProps { sorts: Sort[] filters: Filter[] onAddColumn?: () => void onAddRow?: () => void } const DefaultHeader: FC<DefaultHeaderProps> = ({ sorts, filters, onAddColumn, onAddRow }) => { const renderNewColumn = (onAddColumn?: () => void) => { if (!onAddColumn) return null return ( <Button type="text" onClick={onAddColumn}> New Column </Button> ) } const renderAddRow = (onAddRow?: () => void) => { if (!onAddRow) return null return ( <Button size="tiny" icon={<IconPlus size={14} strokeWidth={2} />} onClick={onAddRow}> Insert row </Button> ) } return ( <div className="flex items-center gap-4"> <div className="flex items-center gap-1"> <RefreshButton filters={filters} sorts={sorts} /> <FilterDropdown /> <SortPopover /> </div> <div className="bg-scale-600 h-[50%] w-px"></div> <div className="flex items-center gap-2"> {renderNewColumn(onAddColumn)} {renderAddRow(onAddRow)} </div> </div> ) } interface RowHeaderProps { sorts: Sort[] filters: Filter[] } const RowHeader: FC<RowHeaderProps> = ({ sorts, filters }) => { const state = useTrackedState() const dispatch = useDispatch() const [isExporting, setIsExporting] = useState(false) const { selectedRows, rows: allRows, editable, allRowsSelected, totalRows } = state const onSelectAllRows = () => { dispatch({ type: 'SELECT_ALL_ROWS', payload: { selectedRows: new Set(allRows.map((row) => row.idx)) }, }) } const onRowsDelete = () => { confirmAlert({ title: 'Confirm to delete', message: 'Are you sure you want to delete the selected rows? This action cannot be undone.', onAsyncConfirm: async () => { if (allRowsSelected) { const { error } = filters.length === 0 ? await state.rowService!.truncate() : await state.rowService!.deleteAll(filters) if (error) { if (state.onError) state.onError(error) } else { dispatch({ type: 'REMOVE_ALL_ROWS' }) dispatch({ type: 'SELECTED_ROWS_CHANGE', payload: { selectedRows: new Set() }, }) } } else { const rowIdxs = Array.from(selectedRows) as number[] const rows = allRows.filter((x) => rowIdxs.includes(x.idx)) const { error } = state.rowService!.delete(rows) if (error) { if (state.onError) state.onError(error) } else { dispatch({ type: 'REMOVE_ROWS', payload: { rowIdxs } }) dispatch({ type: 'SELECTED_ROWS_CHANGE', payload: { selectedRows: new Set() }, }) } } }, }) } async function onRowsExportCSV() { setIsExporting(true) const rows = allRowsSelected ? await state.rowService!.fetchAllData(filters, sorts) : allRows.filter((x) => selectedRows.has(x.idx)) const csv = exportRowsToCsv(state.table!.columns, rows) const csvData = new Blob([csv], { type: 'text/csv;charset=utf-8;' }) saveAs(csvData, `${state.table!.name}_rows.csv`) setIsExporting(false) } function deselectRows() { dispatch({ type: 'SELECTED_ROWS_CHANGE', payload: { selectedRows: new Set() }, }) } return ( <div className="flex items-center gap-6"> <div className="flex items-center gap-3"> <Button type="default" style={{ padding: '3px' }} icon={<IconX size="tiny" strokeWidth={2} />} onClick={deselectRows} /> <span className="text-scale-1200 text-xs"> {allRowsSelected ? `${totalRows} rows selected` : selectedRows.size > 1 ? `${selectedRows.size} rows selected` : `${selectedRows.size} row selected`} </span> {!allRowsSelected && ( <Button type="link" onClick={() => onSelectAllRows()}> Select all {totalRows} rows </Button> )} </div> <div className="h-[20px] border-r border-gray-700" /> <div className="flex items-center gap-2"> <Button type="primary" size="tiny" icon={<IconDownload />} loading={isExporting} disabled={isExporting} onClick={onRowsExportCSV} > Export to CSV </Button> {editable && ( <Button type="default" size="tiny" icon={<IconTrash size="tiny" />} onClick={onRowsDelete} > {allRowsSelected ? `Delete ${totalRows} rows` : selectedRows.size > 1 ? `Delete ${selectedRows.size} rows` : `Delete ${selectedRows.size} row`} </Button> )} </div> </div> ) }
studio/components/grid/components/header/Header.tsx
1
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.999148964881897, 0.1454036384820938, 0.00016686346498318017, 0.0035368159878998995, 0.33612239360809326 ]
{ "id": 3, "code_window": [ " })\n", " }\n", "\n", " async function onRowsExportCSV() {\n", " setIsExporting(true)\n", " const rows = allRowsSelected\n", " ? await state.rowService!.fetchAllData(filters, sorts)\n", " : allRows.filter((x) => selectedRows.has(x.idx))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (allRowsSelected && totalRows > MAX_EXPORT_ROW_COUNT) {\n", " ui.setNotification({\n", " category: 'error',\n", " message: `Sorry! We're unable to support exporting of CSV for row counts larger than ${MAX_EXPORT_ROW_COUNT.toLocaleString()} at the moment.`,\n", " })\n", " return setIsExporting(false)\n", " }\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 145 }
import Link from 'next/link' import { useState, useEffect } from 'react' import { useRouter } from 'next/router' import { Button, IconCheckSquare, Loading } from '@supabase/ui' import { useProfile, useStore } from 'hooks' import { auth } from 'lib/gotrue' import { API_URL } from 'lib/constants' import { get, post, delete_ } from 'lib/common/fetch' interface ITokenInfo { organization_name?: string | undefined token_does_not_exist?: boolean email_match?: boolean authorized_user?: boolean expired_token?: boolean invite_id?: number } type TokenInfo = ITokenInfo | undefined const JoinOrganizationPage = () => { const router = useRouter() const { slug, token } = router.query const { ui, app } = useStore() const { profile } = useProfile() const [isSubmitting, setIsSubmitting] = useState(false) const [error, setError] = useState(false) const [tokenValidationInfo, setTokenValidationInfo] = useState<TokenInfo>(undefined) const [tokenInfoLoaded, setTokenInfoLoaded] = useState(false) const { token_does_not_exist, email_match, expired_token, organization_name, invite_id } = tokenValidationInfo || {} const loginRedirectLink = `/?next=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}` useEffect(() => { const fetchTokenInfo = async () => { await ui.load() const response = await get(`${API_URL}/organizations/${slug}/members/join?token=${token}`) if (response.error) { setError(response.error) setTokenInfoLoaded(true) } else { setTokenInfoLoaded(true) setTokenValidationInfo(response) } } if (!tokenInfoLoaded && token) { fetchTokenInfo() } /** * if params are empty then redirect * user to the homepage of app */ // if (!slug && !token) router.push('/') }, [token, router.asPath]) async function handleJoinOrganization() { setIsSubmitting(true) const response = await post(`${API_URL}/organizations/${slug}/members/join?token=${token}`, {}) if (response.error) { ui.setNotification({ category: 'error', message: `Failed to join organization: ${response.error.message}`, }) setIsSubmitting(false) } else { setIsSubmitting(false) app.onOrgAdded(response) router.push('/') } } async function handleDeclineJoinOrganization() { setIsSubmitting(true) const response = await delete_( `${API_URL}/organizations/${slug}/members/invite?invited_id=${invite_id}`, {} ) if (response.error) { ui.setNotification({ category: 'error', message: `Failed to decline invitation: ${response.error.message}`, }) setIsSubmitting(false) } else { setIsSubmitting(false) router.push('/') } } const isError = error || !!(tokenInfoLoaded && token_does_not_exist) || (tokenInfoLoaded && !email_match) || (tokenInfoLoaded && expired_token) const ErrorMessage = () => { const Container = ({ children }: { children: React.ReactNode }) => ( <div className={[ 'flex flex-col items-center justify-center gap-3 text-sm', isError ? 'text-scale-1100' : 'text-scale-1200', ].join(' ')} > {children} </div> ) const message = error ? ( <p>There was an error requesting details for this invitation.</p> ) : token_does_not_exist ? ( <> <p>The invite token is invalid.</p> <p className="text-scale-900"> Try copying and pasting the link from the invite email, or ask the organization owner to invite you again. </p> </> ) : !email_match ? ( <> <p> Your email address {profile?.primary_email} does not match the email address this invitation was sent to. </p> <p className="text-scale-900"> To accept this invitation, you will need to{' '} <a className="text-brand-900 cursor-pointer" onClick={async () => { await auth.signOut() router.reload() }} > sign out </a>{' '} and then sign in or create a new account using the same email address used in the invitation. </p> </> ) : expired_token ? ( <> <p>The invite token has expired.</p> <p className="text-scale-900">Please request a new one from the organization owner.</p> </> ) : ( '' ) return isError ? <Container>{message}</Container> : null } const Content = () => ( <> <div className="flex flex-col gap-2 px-6 py-8"> <> <p className="text-scale-1200 text-sm">You have been invited to join </p> {organization_name ? ( <> <p className="text-scale-1200 text-3xl"> {organization_name ? `${organization_name}` : 'an organization'}{' '} </p> {!token_does_not_exist && ( <p className="text-scale-900 text-sm">an organization on Supabase</p> )} </> ) : ( <> <p className="text-scale-1200 text-3xl">{'an organization'}</p> </> )} {slug && <p className="text-scale-900 text-xs">{`organization slug: ${slug}`}</p>} </> </div> <div className={['border-scale-400 border-t', isError ? 'bg-sand-100' : 'bg-transparent'].join( ' ' )} > <div className="flex flex-col gap-4 px-6 py-4 "> {profile && !isError && ( <div className="flex flex-row items-center justify-center gap-3"> <Button onClick={handleDeclineJoinOrganization} htmlType="submit" type="default"> Decline </Button> <Button onClick={handleJoinOrganization} htmlType="submit" loading={isSubmitting} type="primary" icon={<IconCheckSquare />} > Join organization </Button> </div> )} {tokenInfoLoaded && <ErrorMessage />} {!profile && ( <div className="flex flex-col gap-3"> <p className="text-scale-900 text-xs"> You will need to sign in to accept this invitation </p> <div className="flex justify-center gap-3"> <Link passHref href={loginRedirectLink}> <Button as="a" type="default"> Sign in </Button> </Link> <Link passHref href={loginRedirectLink}> <Button as="a" type="default"> Create an account </Button> </Link> </div> </div> )} </div> </div> </> ) return ( <div className={[ 'bg-scale-200 flex h-full min-h-screen', 'w-full flex-col place-items-center', 'items-center justify-center gap-8 px-5', ].join(' ')} > <Link href="/"> <a className="flex items-center justify-center gap-4"> <img src="/img/supabase-logo.svg" alt="Supabase" className="block h-[24px] cursor-pointer rounded" /> </a> </Link> <div className=" bg-scale-100 border-scale-400 mx-auto overflow-hidden rounded-md border text-center shadow md:w-[400px] " > <Loading active={!tokenInfoLoaded}> <Content /> </Loading> </div> </div> ) } export default JoinOrganizationPage
studio/pages/join/index.tsx
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00019028699898626655, 0.00017237249994650483, 0.00016632780898362398, 0.0001715622202027589, 0.000005386424163589254 ]
{ "id": 3, "code_window": [ " })\n", " }\n", "\n", " async function onRowsExportCSV() {\n", " setIsExporting(true)\n", " const rows = allRowsSelected\n", " ? await state.rowService!.fetchAllData(filters, sorts)\n", " : allRows.filter((x) => selectedRows.has(x.idx))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (allRowsSelected && totalRows > MAX_EXPORT_ROW_COUNT) {\n", " ui.setNotification({\n", " category: 'error',\n", " message: `Sorry! We're unable to support exporting of CSV for row counts larger than ${MAX_EXPORT_ROW_COUNT.toLocaleString()} at the moment.`,\n", " })\n", " return setIsExporting(false)\n", " }\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 145 }
import { createContext, useContext, useEffect, useState } from 'react' interface UseThemeProps { isDarkMode?: boolean toggleTheme: () => void } interface ThemeProviderProps { children?: any } export const ThemeContext = createContext<UseThemeProps>({ isDarkMode: true, toggleTheme: () => {}, }) export const useTheme = () => useContext(ThemeContext) export const ThemeProvider = ({ children }: ThemeProviderProps) => { const [isDarkMode, setIsDarkMode] = useState(false) useEffect(() => { const key = localStorage.getItem('supabaseDarkMode') // Default to dark mode if no preference config setIsDarkMode(!key || key === 'true') }, []) const toggleTheme = () => { setIsDarkMode(!isDarkMode) } return ( <> <ThemeContext.Provider value={{ isDarkMode, toggleTheme, }} > {children} </ThemeContext.Provider> </> ) }
apps/www/components/Providers/index.tsx
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0005291671841405332, 0.0002444511919748038, 0.0001678710978012532, 0.00017484334239270538, 0.0001423890789737925 ]
{ "id": 3, "code_window": [ " })\n", " }\n", "\n", " async function onRowsExportCSV() {\n", " setIsExporting(true)\n", " const rows = allRowsSelected\n", " ? await state.rowService!.fetchAllData(filters, sorts)\n", " : allRows.filter((x) => selectedRows.has(x.idx))\n" ], "labels": [ "keep", "keep", "keep", "keep", "add", "keep", "keep", "keep" ], "after_edit": [ "\n", " if (allRowsSelected && totalRows > MAX_EXPORT_ROW_COUNT) {\n", " ui.setNotification({\n", " category: 'error',\n", " message: `Sorry! We're unable to support exporting of CSV for row counts larger than ${MAX_EXPORT_ROW_COUNT.toLocaleString()} at the moment.`,\n", " })\n", " return setIsExporting(false)\n", " }\n", "\n" ], "file_path": "studio/components/grid/components/header/Header.tsx", "type": "add", "edit_start_line_idx": 145 }
export const WARNING_MESSAGE = { title: 'Edge Functions are experimental until 1st August 2022. There will be breaking changes.', }
studio/components/interfaces/Functions/Functions.constants.ts
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00016572480672039092, 0.00016572480672039092, 0.00016572480672039092, 0.00016572480672039092, 0 ]
{ "id": 4, "code_window": [ "\n", " async fetchAllData(filters: Filter[], sorts: Sort[]) {\n", " // Paginate the request for very large tables to prevent stalling of API\n", " // [TODO] Note we probably still need a fail-safe if the table is just\n", " // too large for a browser to keep all the rows in memory before exporting\n", " // Either that or export as multiple CSV sheets, max n rows\n", " const rows: any[] = []\n", "\n", " let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select()\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "studio/components/grid/services/row/SqlRowService.ts", "type": "replace", "edit_start_line_idx": 117 }
import { IRowService } from '.' import { Filter, ServiceError, Sort, SupaRow, SupaTable } from '../../types' import { ERROR_PRIMARY_KEY_NOTFOUND, SupabaseGridQueue } from '../../constants' import Query from '../../query' import { isNumericalColumn } from '../../utils' import { useDispatch } from 'components/grid/store' export class SqlRowService implements IRowService { protected query = new Query() protected dispatch = useDispatch() constructor( protected table: SupaTable, protected onSqlQuery: (query: string) => Promise<{ data?: any; error?: any }>, protected onError: (error: any) => void ) {} async count(filters: Filter[]) { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).count() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) const query = queryChains.toSql() const { data, error } = await this.onSqlQuery(query) if (error) { return { error } } else { if (data?.length == 1) { return { data: data[0].count } } else { return { error: { message: 'fetch rows count failed' } } } } } async create(row: SupaRow) { return { error: { message: 'not implemented' } } } delete(rows: SupaRow[]) { const { primaryKeys, error } = this.getPrimaryKeys() if (error) return { error } let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).delete() primaryKeys!.forEach((key) => { const primaryKeyValues = rows.map((x) => x[key]) queryChains = queryChains.filter(key, 'in', primaryKeyValues) }) const query = queryChains.toSql() SupabaseGridQueue.add(async () => { const { error } = await this.onSqlQuery(query) if (error) throw error }).catch((error) => { this.onError(error) }) return {} } // For deleting all rows based on a given filter async deleteAll(filters: Filter[]) { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).delete() filters .filter((x) => x.value && x.value !== '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) const query = queryChains.toSql() return await this.onSqlQuery(query) } // For deleting all rows without any filter (clear entire table) async truncate() { let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).truncate() const query = queryChains.toSql() return await this.onSqlQuery(query) } async fetchPage(page: number, rowsPerPage: number, filters: Filter[], sorts: Sort[]) { const pageFromZero = page > 0 ? page - 1 : page const from = pageFromZero * rowsPerPage const to = (pageFromZero + 1) * rowsPerPage - 1 let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) sorts.forEach((x) => { queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst) }) const query = queryChains.range(from, to).toSql() const { data, error } = await this.onSqlQuery(query) if (error) { this.onError(error) return { data: { rows: [] } } } else { const rows = data?.map((x: any, index: number) => { return { idx: index, ...x } as SupaRow }) return { data: { rows } } } } async fetchAllData(filters: Filter[], sorts: Sort[]) { // Paginate the request for very large tables to prevent stalling of API // [TODO] Note we probably still need a fail-safe if the table is just // too large for a browser to keep all the rows in memory before exporting // Either that or export as multiple CSV sheets, max n rows const rows: any[] = [] let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select() filters .filter((x) => x.value && x.value != '') .forEach((x) => { const value = this.formatFilterValue(x) queryChains = queryChains.filter(x.column, x.operator, value) }) sorts.forEach((x) => { queryChains = queryChains.order(x.column, x.ascending, x.nullsFirst) }) // Starting from page 0, fetch 500 records per call let page = -1 let from = 0 let to = 0 let pageData = [] const rowsPerPage = 500 await (async () => { do { page += 1 from = page * rowsPerPage to = (page + 1) * rowsPerPage - 1 const query = queryChains.range(from, to).toSql() const { data, error } = await this.onSqlQuery(query) if (error) { this.onError(error) return { data: { rows: [] } } } else { rows.push(...data) pageData = data } } while (pageData.length === rowsPerPage) })() return rows } update(row: SupaRow, changedColumn?: string, onRowUpdate?: (value: any) => void) { const { primaryKeys, error } = this.getPrimaryKeys() if (error) { return { error } } const { idx, ...value } = row const matchValues: any = {} primaryKeys!.forEach((key) => { matchValues[key] = row[key] // fix: https://github.com/supabase/grid/issues/94 // remove primary key from updated value object delete value[key] }) const query = this.query .from(this.table.name, this.table.schema ?? undefined) .update( changedColumn ? { [changedColumn]: value[changedColumn], } : value, { returning: true } ) .match(matchValues) .toSql() SupabaseGridQueue.add(async () => { const { data, error } = await this.onSqlQuery(query) if (error) throw error if (onRowUpdate) onRowUpdate({ row: data[0], idx }) }).catch((error) => { this.onError(error) }) return {} } getPrimaryKeys(): { primaryKeys?: string[]; error?: ServiceError } { const pkColumns = this.table.columns.filter((x) => x.isPrimaryKey) if (!pkColumns || pkColumns.length == 0) { return { error: { message: ERROR_PRIMARY_KEY_NOTFOUND } } } return { primaryKeys: pkColumns.map((x) => x.name) } } /** * temporary fix until we impliment a better filter UI * which validate input value base on the column type */ formatFilterValue(filter: Filter) { const column = this.table.columns.find((x) => x.name == filter.column) if (column && isNumericalColumn(column.format)) { const numberValue = Number(filter.value) if (Number.isNaN(numberValue)) return filter.value else return Number(filter.value) } return filter.value } }
studio/components/grid/services/row/SqlRowService.ts
1
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.9983148574829102, 0.4567723572254181, 0.0001658292894717306, 0.08235576748847961, 0.4786815941333771 ]
{ "id": 4, "code_window": [ "\n", " async fetchAllData(filters: Filter[], sorts: Sort[]) {\n", " // Paginate the request for very large tables to prevent stalling of API\n", " // [TODO] Note we probably still need a fail-safe if the table is just\n", " // too large for a browser to keep all the rows in memory before exporting\n", " // Either that or export as multiple CSV sheets, max n rows\n", " const rows: any[] = []\n", "\n", " let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select()\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "studio/components/grid/services/row/SqlRowService.ts", "type": "replace", "edit_start_line_idx": 117 }
import { createContext, useEffect, useContext, useState, ChangeEvent } from 'react' import { useRouter } from 'next/router' import { observer, useLocalObservable } from 'mobx-react-lite' import { Button, Input, Select } from '@supabase/ui' import { runInAction } from 'mobx' import { API_URL } from 'lib/constants' import { post } from 'lib/common/fetch' import { useStore } from 'hooks' import VercelIntegrationLayout from 'components/layouts/VercelIntegrationLayout' const PageContext = createContext(null) function SetupOrg() { const PageState = useLocalObservable(() => ({ token: '', teamId: '', externalId: '', configurationId: '', next: '', selectedOrg: undefined, vercelProjectId: undefined, selectMenuOpened: false, shouldShowOrgCreationUI: false, get queryParams() { return { token: this.token, teamId: this.teamId, 'external-id': this.externalId, configurationId: this.configurationId, // @ts-ignore supabaseOrgId: this.selectedOrg.id, vercelProjectId: this.vercelProjectId, next: this.next, } }, get canContinue() { return !!this.selectedOrg }, loadInitialData() { this.getQueryParams() }, getQueryParams() { const params = new URLSearchParams(window.location.search) this.configurationId = params.get('configurationId') as string this.vercelProjectId = params.get('vercelProjectId') as any this.next = params.get('next') as string this.externalId = params.get('external-id') as string this.token = params.get('token') as string this.teamId = params.get('teamId') as string }, toggleSelectMenu(value: any) { this.selectMenuOpened = value }, })) const { app } = useStore() useEffect(() => { PageState.loadInitialData() const sortedOrganizations = app.organizations.list() PageState.shouldShowOrgCreationUI = sortedOrganizations?.length == 0 }, []) return ( // @ts-ignore <PageContext.Provider value={PageState}> <VercelIntegrationLayout> {PageState.shouldShowOrgCreationUI ? <CreateOrganization /> : <OrgSelection />} </VercelIntegrationLayout> </PageContext.Provider> ) } export default observer(SetupOrg) const CreateOrganization = observer(({}) => { const PageState: any = useContext(PageContext) const router = useRouter() const { ui, app } = useStore() const sortedOrganizations = app.organizations.list() const [orgName, setOrgName] = useState('') const [loading, setLoading] = useState(false) async function onClick() { setLoading(true) const response = await post(`${API_URL}/organizations`, { name: orgName, }) if (response.error) { ui.setNotification({ category: 'error', message: `Failed to set up organization: ${response.error.message}`, }) setLoading(false) } else { const org = response PageState.selectedOrg = org const query = new URLSearchParams(PageState.queryParams).toString() router.push(`/vercel/setupProject?${query}`) } } function onOrgNameChange(e: any) { setOrgName(e.target.value) } return ( <div className=""> {sortedOrganizations?.length > 0 ? ( <p className="mb-2">Create a new organization</p> ) : ( <> <p className="mb-2">You do not have any organization</p> <p>You will need an organization to deploy this project</p> </> )} <div className="py-4"> <Input autoFocus label="Name" type="text" placeholder="Organization name" descriptionText="What's the name of your company or team?" value={orgName} onChange={onOrgNameChange} /> </div> <Button disabled={loading || orgName == ''} loading={loading} onClick={onClick}> Create organization </Button> </div> ) }) const OrgSelection = observer(({}) => { const PageState: any = useContext(PageContext) const router = useRouter() const [loading, setLoading] = useState(false) const { app } = useStore() const sortedOrganizations = app.organizations.list() useEffect(() => { if (!PageState.selectedOrg) { PageState.selectedOrg = sortedOrganizations?.length > 0 ? sortedOrganizations[0] : undefined } }, [sortedOrganizations]) function onContinue() { setLoading(true) const query = new URLSearchParams(PageState.queryParams).toString() router.push(`/vercel/setupProject?${query}`) } function onNewOrg() { runInAction(() => { PageState.shouldShowOrgCreationUI = true }) } function onOrgSelect(e: ChangeEvent<HTMLSelectElement>) { const selectedOrg = sortedOrganizations.find((x: any) => x.slug === e.target.value) PageState.selectedOrg = selectedOrg } return ( <div className=""> <div className="mt-1 mb-8 relative"> <Select label="Choose an organization" value={PageState.selectedOrg?.slug} onChange={onOrgSelect} > {sortedOrganizations?.map((x) => { return ( <Select.Option key={x.id} value={x.slug}> {x.name} </Select.Option> ) })} </Select> </div> <div className="flex flex-col space-y-4"> <Button disabled={loading || !PageState.canContinue} loading={loading} onClick={onContinue} block > Continue </Button> <Button type="secondary" onClick={onNewOrg} block> New Organization </Button> </div> </div> ) })
studio/pages/vercel/setupOrg.tsx
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.0007919842028059065, 0.00020946955191902816, 0.00016384547052439302, 0.00017196625412907451, 0.0001362046750728041 ]
{ "id": 4, "code_window": [ "\n", " async fetchAllData(filters: Filter[], sorts: Sort[]) {\n", " // Paginate the request for very large tables to prevent stalling of API\n", " // [TODO] Note we probably still need a fail-safe if the table is just\n", " // too large for a browser to keep all the rows in memory before exporting\n", " // Either that or export as multiple CSV sheets, max n rows\n", " const rows: any[] = []\n", "\n", " let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select()\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "studio/components/grid/services/row/SqlRowService.ts", "type": "replace", "edit_start_line_idx": 117 }
# To learn about Buck see [Docs](https://buckbuild.com/). # To run your application with Buck: # - install Buck # - `npm start` - to start the packager # - `cd android` # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"` # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck # - `buck install -r android/app` - compile, install and run application # load(":build_defs.bzl", "create_aar_targets", "create_jar_targets") lib_deps = [] create_aar_targets(glob(["libs/*.aar"])) create_jar_targets(glob(["libs/*.jar"])) android_library( name = "all-libs", exported_deps = lib_deps, ) android_library( name = "app-code", srcs = glob([ "src/main/java/**/*.java", ]), deps = [ ":all-libs", ":build_config", ":res", ], ) android_build_config( name = "build_config", package = "com.reactnativetodolist", ) android_resource( name = "res", package = "com.reactnativetodolist", res = "src/main/res", ) android_binary( name = "app", keystore = "//android/keystores:debug", manifest = "src/main/AndroidManifest.xml", package_type = "debug", deps = [ ":app-code", ], )
examples/todo-list/react-native-todo-list/android/app/_BUCK
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00017172275693155825, 0.00016852786939125508, 0.00016485106607433408, 0.00016895578301046044, 0.000002595976411612355 ]
{ "id": 4, "code_window": [ "\n", " async fetchAllData(filters: Filter[], sorts: Sort[]) {\n", " // Paginate the request for very large tables to prevent stalling of API\n", " // [TODO] Note we probably still need a fail-safe if the table is just\n", " // too large for a browser to keep all the rows in memory before exporting\n", " // Either that or export as multiple CSV sheets, max n rows\n", " const rows: any[] = []\n", "\n", " let queryChains = this.query.from(this.table.name, this.table.schema ?? undefined).select()\n" ], "labels": [ "keep", "keep", "keep", "replace", "replace", "replace", "keep", "keep", "keep" ], "after_edit": [], "file_path": "studio/components/grid/services/row/SqlRowService.ts", "type": "replace", "edit_start_line_idx": 117 }
<?xml version="1.0" encoding="UTF-8"?> <svg version="1.1" viewBox="0 0 261.76 226.69" xmlns="http://www.w3.org/2000/svg"><g transform="matrix(1.3333 0 0 -1.3333 -76.311 313.34)"><g transform="translate(178.06 235.01)"><path d="m0 0-22.669-39.264-22.669 39.264h-75.491l98.16-170.02 98.16 170.02z" fill="#41b883"/></g><g transform="translate(178.06 235.01)"><path d="m0 0-22.669-39.264-22.669 39.264h-36.227l58.896-102.01 58.896 102.01z" fill="#34495e"/></g></g></svg>
studio/public/img/libraries/vuejs-icon.svg
0
https://github.com/supabase/supabase/commit/62bc3561a8700cba110b321b756fbb3c82eb03be
[ 0.00017372494039591402, 0.00017372494039591402, 0.00017372494039591402, 0.00017372494039591402, 0 ]
{ "id": 0, "code_window": [ "\n", " return (\n", " <WithFeatureToggle featureToggle={editorsCanAdmin}>\n", " <td>\n", " <div className=\"gf-form\">\n", " {signedInUserIsTeamAdmin && (\n", " <Select\n", " isSearchable={false}\n", " options={teamsPermissionLevels}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td className=\"width-5 team-permissions\">\n" ], "file_path": "public/app/features/teams/TeamMemberRow.tsx", "type": "replace", "edit_start_line_idx": 42 }
import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { DeleteButton, Select, SelectOptionItem } from '@grafana/ui'; import { TeamMember, teamsPermissionLevels } from 'app/types'; import { WithFeatureToggle } from 'app/core/components/WithFeatureToggle'; import { updateTeamMember, removeTeamMember } from './state/actions'; import { TagBadge } from 'app/core/components/TagFilter/TagBadge'; export interface Props { member: TeamMember; syncEnabled: boolean; editorsCanAdmin: boolean; signedInUserIsTeamAdmin: boolean; removeTeamMember?: typeof removeTeamMember; updateTeamMember?: typeof updateTeamMember; } export class TeamMemberRow extends PureComponent<Props> { constructor(props: Props) { super(props); this.renderLabels = this.renderLabels.bind(this); this.renderPermissions = this.renderPermissions.bind(this); } onRemoveMember(member: TeamMember) { this.props.removeTeamMember(member.userId); } onPermissionChange = (item: SelectOptionItem, member: TeamMember) => { const permission = item.value; const updatedTeamMember = { ...member, permission }; this.props.updateTeamMember(updatedTeamMember); }; renderPermissions(member: TeamMember) { const { editorsCanAdmin, signedInUserIsTeamAdmin } = this.props; const value = teamsPermissionLevels.find(dp => dp.value === member.permission); return ( <WithFeatureToggle featureToggle={editorsCanAdmin}> <td> <div className="gf-form"> {signedInUserIsTeamAdmin && ( <Select isSearchable={false} options={teamsPermissionLevels} onChange={item => this.onPermissionChange(item, member)} className="gf-form-select-box__control--menu-right" value={value} /> )} {!signedInUserIsTeamAdmin && <span>{value.label}</span>} </div> </td> </WithFeatureToggle> ); } renderLabels(labels: string[]) { if (!labels) { return <td />; } return ( <td> {labels.map(label => ( <TagBadge key={label} label={label} removeIcon={false} count={0} onClick={() => {}} /> ))} </td> ); } render() { const { member, syncEnabled, signedInUserIsTeamAdmin } = this.props; return ( <tr key={member.userId}> <td className="width-4 text-center"> <img className="filter-table__avatar" src={member.avatarUrl} /> </td> <td>{member.login}</td> <td>{member.email}</td> {this.renderPermissions(member)} {syncEnabled && this.renderLabels(member.labels)} <td className="text-right"> <DeleteButton onConfirm={() => this.onRemoveMember(member)} disabled={!signedInUserIsTeamAdmin} /> </td> </tr> ); } } function mapStateToProps(state) { return {}; } const mapDispatchToProps = { removeTeamMember, updateTeamMember, }; export default connect( mapStateToProps, mapDispatchToProps )(TeamMemberRow);
public/app/features/teams/TeamMemberRow.tsx
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.997669517993927, 0.26661378145217896, 0.00016240173135884106, 0.0019871320109814405, 0.4339583218097687 ]
{ "id": 0, "code_window": [ "\n", " return (\n", " <WithFeatureToggle featureToggle={editorsCanAdmin}>\n", " <td>\n", " <div className=\"gf-form\">\n", " {signedInUserIsTeamAdmin && (\n", " <Select\n", " isSearchable={false}\n", " options={teamsPermissionLevels}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td className=\"width-5 team-permissions\">\n" ], "file_path": "public/app/features/teams/TeamMemberRow.tsx", "type": "replace", "edit_start_line_idx": 42 }
// cgo -godefs types_darwin.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. // +build amd64,darwin package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 ) type ( _C_short int16 _C_int int32 _C_long int64 _C_long_long int64 ) type Timespec struct { Sec int64 Nsec int64 } type Timeval struct { Sec int64 Usec int32 _ [4]byte } type Timeval32 struct { Sec int32 Usec int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int64 Ixrss int64 Idrss int64 Isrss int64 Minflt int64 Majflt int64 Nswap int64 Inblock int64 Oublock int64 Msgsnd int64 Msgrcv int64 Nsignals int64 Nvcsw int64 Nivcsw int64 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 _ [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 } type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid Fsid Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 } type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 } type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 } type Radvisory_t struct { Offset int64 Count int32 _ [4]byte } type Fbootstraptransfer_t struct { Offset int64 Length uint64 Buffer *byte } type Log2phys_t struct { Flags uint32 _ [8]byte _ [8]byte } type Fsid struct { Val [2]int32 } type Dirent struct { Ino uint64 Seekoff uint64 Reclen uint16 Namlen uint16 Type uint8 Name [1024]int8 _ [3]byte } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [12]int8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint64 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 _ [4]byte Iov *Iovec Iovlen int32 _ [4]byte Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 } type Inet4Pktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type Inet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type ICMPv6Filter struct { Filt [8]uint32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x6c SizeofSockaddrUnix = 0x6a SizeofSockaddrDatalink = 0x14 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x30 SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 ) const ( PTRACE_TRACEME = 0x0 PTRACE_CONT = 0x7 PTRACE_KILL = 0x8 ) type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte } type FdSet struct { Bits [32]int32 } const ( SizeofIfMsghdr = 0x70 SizeofIfData = 0x60 SizeofIfaMsghdr = 0x14 SizeofIfmaMsghdr = 0x10 SizeofIfmaMsghdr2 = 0x14 SizeofRtMsghdr = 0x5c SizeofRtMetrics = 0x38 ) type IfMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Data IfData } type IfData struct { Type uint8 Typelen uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Unused1 uint8 Mtu uint32 Metric uint32 Baudrate uint32 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Recvtiming uint32 Xmittiming uint32 Lastchange Timeval32 Unused2 uint32 Hwassist uint32 Reserved1 uint32 Reserved2 uint32 } type IfaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Metric int32 } type IfmaMsghdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte } type IfmaMsghdr2 struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 _ [2]byte Refcount int32 } type RtMsghdr struct { Msglen uint16 Version uint8 Type uint8 Index uint16 _ [2]byte Flags int32 Addrs int32 Pid int32 Seq int32 Errno int32 Use int32 Inits uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Hopcount uint32 Expire int32 Recvpipe uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Pksent uint32 Filler [4]uint32 } const ( SizeofBpfVersion = 0x4 SizeofBpfStat = 0x8 SizeofBpfProgram = 0x10 SizeofBpfInsn = 0x8 SizeofBpfHdr = 0x14 ) type BpfVersion struct { Major uint16 Minor uint16 } type BpfStat struct { Recv uint32 Drop uint32 } type BpfProgram struct { Len uint32 _ [4]byte Insns *BpfInsn } type BpfInsn struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type BpfHdr struct { Tstamp Timeval32 Caplen uint32 Datalen uint32 Hdrlen uint16 _ [2]byte } type Termios struct { Iflag uint64 Oflag uint64 Cflag uint64 Lflag uint64 Cc [20]uint8 _ [4]byte Ispeed uint64 Ospeed uint64 } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x80 AT_SYMLINK_FOLLOW = 0x40 AT_SYMLINK_NOFOLLOW = 0x20 ) type PollFd struct { Fd int32 Events int16 Revents int16 } const ( POLLERR = 0x8 POLLHUP = 0x10 POLLIN = 0x1 POLLNVAL = 0x20 POLLOUT = 0x4 POLLPRI = 0x2 POLLRDBAND = 0x80 POLLRDNORM = 0x40 POLLWRBAND = 0x100 POLLWRNORM = 0x4 ) type Utsname struct { Sysname [256]byte Nodename [256]byte Release [256]byte Version [256]byte Machine [256]byte }
vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00022139462816994637, 0.00017216084233950824, 0.00016360098379664123, 0.0001711440272629261, 0.000008463395715807565 ]
{ "id": 0, "code_window": [ "\n", " return (\n", " <WithFeatureToggle featureToggle={editorsCanAdmin}>\n", " <td>\n", " <div className=\"gf-form\">\n", " {signedInUserIsTeamAdmin && (\n", " <Select\n", " isSearchable={false}\n", " options={teamsPermissionLevels}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td className=\"width-5 team-permissions\">\n" ], "file_path": "public/app/features/teams/TeamMemberRow.tsx", "type": "replace", "edit_start_line_idx": 42 }
// Rotated & Flipped Icons // ------------------------- .#{$fa-css-prefix}-rotate-90 { @include fa-icon-rotate(90deg, 1); } .#{$fa-css-prefix}-rotate-180 { @include fa-icon-rotate(180deg, 2); } .#{$fa-css-prefix}-rotate-270 { @include fa-icon-rotate(270deg, 3); } .#{$fa-css-prefix}-flip-horizontal { @include fa-icon-flip(-1, 1, 0); } .#{$fa-css-prefix}-flip-vertical { @include fa-icon-flip(1, -1, 2); } // Hook for IE8-9 // ------------------------- :root .#{$fa-css-prefix}-rotate-90, :root .#{$fa-css-prefix}-rotate-180, :root .#{$fa-css-prefix}-rotate-270, :root .#{$fa-css-prefix}-flip-horizontal, :root .#{$fa-css-prefix}-flip-vertical { filter: none; }
public/sass/base/font-awesome/_rotated-flipped.scss
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017620919970795512, 0.00017416119226254523, 0.00017260645108763129, 0.00017391456640325487, 0.0000015292340549422079 ]
{ "id": 0, "code_window": [ "\n", " return (\n", " <WithFeatureToggle featureToggle={editorsCanAdmin}>\n", " <td>\n", " <div className=\"gf-form\">\n", " {signedInUserIsTeamAdmin && (\n", " <Select\n", " isSearchable={false}\n", " options={teamsPermissionLevels}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td className=\"width-5 team-permissions\">\n" ], "file_path": "public/app/features/teams/TeamMemberRow.tsx", "type": "replace", "edit_start_line_idx": 42 }
+++ title = "Developing Plugins" type = "docs" [menu.docs] parent = "plugins" identifier = "developing" weight = 3 +++
docs/sources/plugins/developing/index.md
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0001754380064085126, 0.0001754380064085126, 0.0001754380064085126, 0.0001754380064085126, 0 ]
{ "id": 1, "code_window": [ " className=\"page-action-bar__spacer\"\n", " />\n", " <a\n", " className=\"btn btn-primary disabled\"\n", " href=\"org/teams/new\"\n", " >\n", " New team\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " href=\"#\"\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamList.test.tsx.snap", "type": "replace", "edit_start_line_idx": 386 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render team members when sync enabled 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={false} > <td> <div className="gf-form" > <span> Member </span> </div> </td> </Component> <td> <TagBadge count={0} key="LDAP" label="LDAP" onClick={[Function]} removeIcon={false} /> </td> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned off should not render permissions 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={false} > <td> <div className="gf-form" > <Select autoFocus={false} backspaceRemovesValue={true} className="gf-form-select-box__control--menu-right" isClearable={false} isDisabled={false} isLoading={false} isMulti={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} openMenuOnFocus={false} options={ Array [ Object { "description": "Is team member", "label": "Member", "value": 0, }, Object { "description": "Can add/remove permissions, members and delete team.", "label": "Admin", "value": 4, }, ] } value={ Object { "description": "Is team member", "label": "Member", "value": 0, } } width={null} /> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned on should render permissions select if user is team admin 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={true} > <td> <div className="gf-form" > <Select autoFocus={false} backspaceRemovesValue={true} className="gf-form-select-box__control--menu-right" isClearable={false} isDisabled={false} isLoading={false} isMulti={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} openMenuOnFocus={false} options={ Array [ Object { "description": "Is team member", "label": "Member", "value": 0, }, Object { "description": "Can add/remove permissions, members and delete team.", "label": "Admin", "value": 4, }, ] } value={ Object { "description": "Is team member", "label": "Member", "value": 0, } } width={null} /> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned on should render span and disable buttons if user is team member 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={true} > <td> <div className="gf-form" > <span> Member </span> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> `;
public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0009080361924134195, 0.0002447274746373296, 0.00016436856822110713, 0.00016998629143927246, 0.0001848907268140465 ]
{ "id": 1, "code_window": [ " className=\"page-action-bar__spacer\"\n", " />\n", " <a\n", " className=\"btn btn-primary disabled\"\n", " href=\"org/teams/new\"\n", " >\n", " New team\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " href=\"#\"\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamList.test.tsx.snap", "type": "replace", "edit_start_line_idx": 386 }
.add-data-source-header { margin-bottom: $space-xl; padding-top: $spacer; text-align: center; } .add-data-source-search { display: flex; justify-content: center; margin-bottom: $space-lg; } .add-data-source-grid { display: grid; grid-template-columns: repeat(2, 1fr); grid-row-gap: 10px; grid-column-gap: 10px; @include media-breakpoint-up(md) { grid-template-columns: repeat(3, 1fr); } } .add-data-source-grid-item { padding: 15px; display: flex; align-items: center; cursor: pointer; background: $card-background; box-shadow: $card-shadow; color: $text-color; &:hover { background: $card-background-hover; color: $text-color-strong; } } .add-data-source-grid-item-text { font-size: $font-size-h5; } .add-data-source-grid-item-logo { margin: 0 $space-md; width: 55px; }
public/sass/components/_add_data_source.scss
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017641698650550097, 0.00017225333431269974, 0.00016880205657798797, 0.00017187937919516116, 0.000002469258106430061 ]
{ "id": 1, "code_window": [ " className=\"page-action-bar__spacer\"\n", " />\n", " <a\n", " className=\"btn btn-primary disabled\"\n", " href=\"org/teams/new\"\n", " >\n", " New team\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " href=\"#\"\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamList.test.tsx.snap", "type": "replace", "edit_start_line_idx": 386 }
// Copyright 2019 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package core import ( "fmt" "reflect" "strings" "time" ) const ( TWOSIDES = iota + 1 ONLYTODB ONLYFROMDB ) // Column defines database column type Column struct { Name string TableName string FieldName string SQLType SQLType IsJSON bool Length int Length2 int Nullable bool Default string Indexes map[string]int IsPrimaryKey bool IsAutoIncrement bool MapType int IsCreated bool IsUpdated bool IsDeleted bool IsCascade bool IsVersion bool DefaultIsEmpty bool EnumOptions map[string]int SetOptions map[string]int DisableTimeZone bool TimeZone *time.Location // column specified time zone Comment string } // NewColumn creates a new column func NewColumn(name, fieldName string, sqlType SQLType, len1, len2 int, nullable bool) *Column { return &Column{ Name: name, TableName: "", FieldName: fieldName, SQLType: sqlType, Length: len1, Length2: len2, Nullable: nullable, Default: "", Indexes: make(map[string]int), IsPrimaryKey: false, IsAutoIncrement: false, MapType: TWOSIDES, IsCreated: false, IsUpdated: false, IsDeleted: false, IsCascade: false, IsVersion: false, DefaultIsEmpty: false, EnumOptions: make(map[string]int), Comment: "", } } // String generate column description string according dialect func (col *Column) String(d Dialect) string { sql := d.QuoteStr() + col.Name + d.QuoteStr() + " " sql += d.SqlType(col) + " " if col.IsPrimaryKey { sql += "PRIMARY KEY " if col.IsAutoIncrement { sql += d.AutoIncrStr() + " " } } if col.Default != "" { sql += "DEFAULT " + col.Default + " " } if d.ShowCreateNull() { if col.Nullable { sql += "NULL " } else { sql += "NOT NULL " } } return sql } // StringNoPk generate column description string according dialect without primary keys func (col *Column) StringNoPk(d Dialect) string { sql := d.QuoteStr() + col.Name + d.QuoteStr() + " " sql += d.SqlType(col) + " " if col.Default != "" { sql += "DEFAULT " + col.Default + " " } if d.ShowCreateNull() { if col.Nullable { sql += "NULL " } else { sql += "NOT NULL " } } return sql } // ValueOf returns column's filed of struct's value func (col *Column) ValueOf(bean interface{}) (*reflect.Value, error) { dataStruct := reflect.Indirect(reflect.ValueOf(bean)) return col.ValueOfV(&dataStruct) } // ValueOfV returns column's filed of struct's value accept reflevt value func (col *Column) ValueOfV(dataStruct *reflect.Value) (*reflect.Value, error) { var fieldValue reflect.Value fieldPath := strings.Split(col.FieldName, ".") if dataStruct.Type().Kind() == reflect.Map { keyValue := reflect.ValueOf(fieldPath[len(fieldPath)-1]) fieldValue = dataStruct.MapIndex(keyValue) return &fieldValue, nil } else if dataStruct.Type().Kind() == reflect.Interface { structValue := reflect.ValueOf(dataStruct.Interface()) dataStruct = &structValue } level := len(fieldPath) fieldValue = dataStruct.FieldByName(fieldPath[0]) for i := 0; i < level-1; i++ { if !fieldValue.IsValid() { break } if fieldValue.Kind() == reflect.Struct { fieldValue = fieldValue.FieldByName(fieldPath[i+1]) } else if fieldValue.Kind() == reflect.Ptr { if fieldValue.IsNil() { fieldValue.Set(reflect.New(fieldValue.Type().Elem())) } fieldValue = fieldValue.Elem().FieldByName(fieldPath[i+1]) } else { return nil, fmt.Errorf("field %v is not valid", col.FieldName) } } if !fieldValue.IsValid() { return nil, fmt.Errorf("field %v is not valid", col.FieldName) } return &fieldValue, nil }
vendor/github.com/go-xorm/core/column.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0013542132219299674, 0.0002443047414999455, 0.00016396438877563924, 0.00017405339167453349, 0.0002776136389002204 ]
{ "id": 1, "code_window": [ " className=\"page-action-bar__spacer\"\n", " />\n", " <a\n", " className=\"btn btn-primary disabled\"\n", " href=\"org/teams/new\"\n", " >\n", " New team\n", " </a>\n", " </div>\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep" ], "after_edit": [ " href=\"#\"\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamList.test.tsx.snap", "type": "replace", "edit_start_line_idx": 386 }
package plugins import ( "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" ) func init() { bus.AddEventListener(handlePluginStateChanged) } func (pm *PluginManager) updateAppDashboards() { pm.log.Debug("Looking for App Dashboard Updates") query := m.GetPluginSettingsQuery{OrgId: 0} if err := bus.Dispatch(&query); err != nil { plog.Error("Failed to get all plugin settings", "error", err) return } for _, pluginSetting := range query.Result { // ignore disabled plugins if !pluginSetting.Enabled { continue } if pluginDef, exist := Plugins[pluginSetting.PluginId]; exist { if pluginDef.Info.Version != pluginSetting.PluginVersion { syncPluginDashboards(pluginDef, pluginSetting.OrgId) } } } } func autoUpdateAppDashboard(pluginDashInfo *PluginDashboardInfoDTO, orgId int64) error { dash, err := loadPluginDashboard(pluginDashInfo.PluginId, pluginDashInfo.Path) if err != nil { return err } plog.Info("Auto updating App dashboard", "dashboard", dash.Title, "newRev", pluginDashInfo.Revision, "oldRev", pluginDashInfo.ImportedRevision) updateCmd := ImportDashboardCommand{ OrgId: orgId, PluginId: pluginDashInfo.PluginId, Overwrite: true, Dashboard: dash.Data, User: &m.SignedInUser{UserId: 0, OrgRole: m.ROLE_ADMIN}, Path: pluginDashInfo.Path, } return bus.Dispatch(&updateCmd) } func syncPluginDashboards(pluginDef *PluginBase, orgId int64) { plog.Info("Syncing plugin dashboards to DB", "pluginId", pluginDef.Id) // Get plugin dashboards dashboards, err := GetPluginDashboards(orgId, pluginDef.Id) if err != nil { plog.Error("Failed to load app dashboards", "error", err) return } // Update dashboards with updated revisions for _, dash := range dashboards { // remove removed ones if dash.Removed { plog.Info("Deleting plugin dashboard", "pluginId", pluginDef.Id, "dashboard", dash.Slug) deleteCmd := m.DeleteDashboardCommand{OrgId: orgId, Id: dash.DashboardId} if err := bus.Dispatch(&deleteCmd); err != nil { plog.Error("Failed to auto update app dashboard", "pluginId", pluginDef.Id, "error", err) return } continue } // update updated ones if dash.ImportedRevision != dash.Revision { if err := autoUpdateAppDashboard(dash, orgId); err != nil { plog.Error("Failed to auto update app dashboard", "pluginId", pluginDef.Id, "error", err) return } } } // update version in plugin_setting table to mark that we have processed the update query := m.GetPluginSettingByIdQuery{PluginId: pluginDef.Id, OrgId: orgId} if err := bus.Dispatch(&query); err != nil { plog.Error("Failed to read plugin setting by id", "error", err) return } appSetting := query.Result cmd := m.UpdatePluginSettingVersionCmd{ OrgId: appSetting.OrgId, PluginId: appSetting.PluginId, PluginVersion: pluginDef.Info.Version, } if err := bus.Dispatch(&cmd); err != nil { plog.Error("Failed to update plugin setting version", "error", err) } } func handlePluginStateChanged(event *m.PluginStateChangedEvent) error { plog.Info("Plugin state changed", "pluginId", event.PluginId, "enabled", event.Enabled) if event.Enabled { syncPluginDashboards(Plugins[event.PluginId], event.OrgId) } else { query := m.GetDashboardsByPluginIdQuery{PluginId: event.PluginId, OrgId: event.OrgId} if err := bus.Dispatch(&query); err != nil { return err } for _, dash := range query.Result { deleteCmd := m.DeleteDashboardCommand{OrgId: dash.OrgId, Id: dash.Id} plog.Info("Deleting plugin dashboard", "pluginId", event.PluginId, "dashboard", dash.Slug) if err := bus.Dispatch(&deleteCmd); err != nil { return err } } } return nil }
pkg/plugins/dashboards_updater.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00029250787338241935, 0.00017732569540385157, 0.00016157508071046323, 0.0001699636923149228, 0.000032119201932800934 ]
{ "id": 2, "code_window": [ " </td>\n", " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 23 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render team members when sync enabled 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={false} > <td> <div className="gf-form" > <span> Member </span> </div> </td> </Component> <td> <TagBadge count={0} key="LDAP" label="LDAP" onClick={[Function]} removeIcon={false} /> </td> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned off should not render permissions 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={false} > <td> <div className="gf-form" > <Select autoFocus={false} backspaceRemovesValue={true} className="gf-form-select-box__control--menu-right" isClearable={false} isDisabled={false} isLoading={false} isMulti={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} openMenuOnFocus={false} options={ Array [ Object { "description": "Is team member", "label": "Member", "value": 0, }, Object { "description": "Can add/remove permissions, members and delete team.", "label": "Admin", "value": 4, }, ] } value={ Object { "description": "Is team member", "label": "Member", "value": 0, } } width={null} /> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned on should render permissions select if user is team admin 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={true} > <td> <div className="gf-form" > <Select autoFocus={false} backspaceRemovesValue={true} className="gf-form-select-box__control--menu-right" isClearable={false} isDisabled={false} isLoading={false} isMulti={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} openMenuOnFocus={false} options={ Array [ Object { "description": "Is team member", "label": "Member", "value": 0, }, Object { "description": "Can add/remove permissions, members and delete team.", "label": "Admin", "value": 4, }, ] } value={ Object { "description": "Is team member", "label": "Member", "value": 0, } } width={null} /> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned on should render span and disable buttons if user is team member 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={true} > <td> <div className="gf-form" > <span> Member </span> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> `;
public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.99176424741745, 0.08388634026050568, 0.00016687746392562985, 0.00031293786014430225, 0.26662030816078186 ]
{ "id": 2, "code_window": [ " </td>\n", " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 23 }
mysql_opendata: build: docker/blocks/mysql_opendata environment: MYSQL_ROOT_PASSWORD: rootpass MYSQL_DATABASE: testdata MYSQL_USER: grafana MYSQL_PASSWORD: password ports: - "3307:3306"
devenv/docker/blocks/mysql_opendata/docker-compose.yaml
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0001653814542805776, 0.0001653814542805776, 0.0001653814542805776, 0.0001653814542805776, 0 ]
{ "id": 2, "code_window": [ " </td>\n", " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 23 }
package eventstream import ( "bytes" "encoding/binary" "hash/crc32" ) const preludeLen = 8 const preludeCRCLen = 4 const msgCRCLen = 4 const minMsgLen = preludeLen + preludeCRCLen + msgCRCLen const maxPayloadLen = 1024 * 1024 * 16 // 16MB const maxHeadersLen = 1024 * 128 // 128KB const maxMsgLen = minMsgLen + maxHeadersLen + maxPayloadLen var crc32IEEETable = crc32.MakeTable(crc32.IEEE) // A Message provides the eventstream message representation. type Message struct { Headers Headers Payload []byte } func (m *Message) rawMessage() (rawMessage, error) { var raw rawMessage if len(m.Headers) > 0 { var headers bytes.Buffer if err := encodeHeaders(&headers, m.Headers); err != nil { return rawMessage{}, err } raw.Headers = headers.Bytes() raw.HeadersLen = uint32(len(raw.Headers)) } raw.Length = raw.HeadersLen + uint32(len(m.Payload)) + minMsgLen hash := crc32.New(crc32IEEETable) binaryWriteFields(hash, binary.BigEndian, raw.Length, raw.HeadersLen) raw.PreludeCRC = hash.Sum32() binaryWriteFields(hash, binary.BigEndian, raw.PreludeCRC) if raw.HeadersLen > 0 { hash.Write(raw.Headers) } // Read payload bytes and update hash for it as well. if len(m.Payload) > 0 { raw.Payload = m.Payload hash.Write(raw.Payload) } raw.CRC = hash.Sum32() return raw, nil } type messagePrelude struct { Length uint32 HeadersLen uint32 PreludeCRC uint32 } func (p messagePrelude) PayloadLen() uint32 { return p.Length - p.HeadersLen - minMsgLen } func (p messagePrelude) ValidateLens() error { if p.Length == 0 || p.Length > maxMsgLen { return LengthError{ Part: "message prelude", Want: maxMsgLen, Have: int(p.Length), } } if p.HeadersLen > maxHeadersLen { return LengthError{ Part: "message headers", Want: maxHeadersLen, Have: int(p.HeadersLen), } } if payloadLen := p.PayloadLen(); payloadLen > maxPayloadLen { return LengthError{ Part: "message payload", Want: maxPayloadLen, Have: int(payloadLen), } } return nil } type rawMessage struct { messagePrelude Headers []byte Payload []byte CRC uint32 }
vendor/github.com/aws/aws-sdk-go/private/protocol/eventstream/message.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00018642510985955596, 0.0001725346373859793, 0.0001644566800678149, 0.00017159101844299585, 0.0000055187019825098105 ]
{ "id": 2, "code_window": [ " </td>\n", " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 23 }
<div class="login container"> <div class="login-content"> <div class="login-branding"> <img class="logo-icon" src="public/img/grafana_icon.svg" alt="Grafana" /> <div class="logo-wordmark" /> </div> <div class="login-outer-box"> <div class="login-inner-box" id="login-view"> <form name="loginForm" class="login-form-group gf-form-group" ng-hide="disableLoginForm"> <div class="login-form"> <input type="text" name="username" class="gf-form-input login-form-input" required ng-model='formModel.user' placeholder={{loginHint}} autofocus autofill-event-fix> </div> <div class="login-form"> <input type="password" name="password" class="gf-form-input login-form-input" required ng-model="formModel.password" id="inputPassword" placeholder="{{passwordHint}}"> </div> <div class="login-button-group"> <button type="submit" class="btn btn-large p-x-2" ng-if="!loggingIn" ng-click="submit();" ng-class="{'btn-inverse': !loginForm.$valid, 'btn-primary': loginForm.$valid}"> Log In </button> <button type="submit" class="btn btn-large p-x-2 btn-inverse btn-loading" ng-if="loggingIn"> Logging In<span>.</span><span>.</span><span>.</span> </button> <div class="small login-button-forgot-password" ng-hide="ldapEnabled || authProxyEnabled"> <a href="user/password/send-reset-email"> Forgot your password? </a> </div> </div> </form> <div class="text-center login-divider" ng-show="oauthEnabled"> <div> <div class="login-divider-line"> </div> </div> <div> <span class="login-divider-text"> <span ng-hide="disableLoginForm">or</span> </span> </div> <div> <div class="login-divider-line"> </div> </div> </div> <div class="clearfix"></div> <div class="login-oauth text-center" ng-show="oauthEnabled"> <a class="btn btn-medium btn-service btn-service--google login-btn" href="login/google" target="_self" ng-if="oauth.google"> <i class="btn-service-icon fa fa-google"></i> Sign in with Google </a> <a class="btn btn-medium btn-service btn-service--github login-btn" href="login/github" target="_self" ng-if="oauth.github"> <i class="btn-service-icon fa fa-github"></i> Sign in with GitHub </a> <a class="btn btn-medium btn-service btn-service--gitlab login-btn" href="login/gitlab" target="_self" ng-if="oauth.gitlab"> <i class="btn-service-icon fa fa-gitlab"></i> Sign in with GitLab </a> <a class="btn btn-medium btn-service btn-service--grafanacom login-btn" href="login/grafana_com" target="_self" ng-if="oauth.grafana_com"> <i class="btn-service-icon"></i> Sign in with Grafana.com </a> <a class="btn btn-medium btn-service btn-service--oauth login-btn" href="login/generic_oauth" target="_self" ng-if="oauth.generic_oauth"> <i class="btn-service-icon fa fa-sign-in"></i> Sign in with {{oauth.generic_oauth.name}} </a> </div> <div class="login-signup-box" ng-show="!disableUserSignUp"> <div class="login-signup-title p-r-1"> New to Grafana? </div> <a href="signup" class="btn btn-medium btn-signup btn-p-x-2"> Sign Up </a> </div> </div> <div class="login-inner-box remove hidden" id="change-password-view"> <div class="text-left login-change-password-info"> <h5>Change Password</h5> Before you can get started with awesome dashboards we need you to make your account more secure by changing your password. <br />You can change your password again later. </div> <form class="login-form-group gf-form-group"> <div class="login-form"> <input type="password" id="newPassword" name="newPassword" class="gf-form-input login-form-input" required ng-model='command.newPassword' placeholder="New password"> </div> <div class="login-form"> <input type="password" name="confirmNew" class="gf-form-input login-form-input" required ng-model="command.confirmNew" placeholder="Confirm new password"> </div> <div class="login-button-group login-button-group--right text-right"> <a class="btn btn-link" ng-click="skip();"> Skip <info-popover mode="no-padding"> If you skip you will be prompted to change password next time you login. </info-popover> </a> <button type="submit" class="btn btn-large p-x-2" ng-click="changePassword();" ng-class="{'btn-inverse': !loginForm.$valid, 'btn-primary': loginForm.$valid}"> Save </button> </div> </form> </div> <div class="clearfix"></div> </div> </div> </div>
public/app/partials/login.html
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00034863350447267294, 0.00020874613255728036, 0.0001610462786629796, 0.00018184543296229094, 0.0000594429366174154 ]
{ "id": 3, "code_window": [ " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n", " <Select\n", " autoFocus={false}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 74 }
.admin-settings-section { color: $variable; font-weight: bold; } td.admin-settings-key { padding-left: 20px; } .admin-list-table { margin-bottom: 20px; } .admin-list-paging { float: right; li { display: inline-block; padding-left: 10px; margin-bottom: 5px; } }
public/sass/pages/_admin.scss
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0001770051894709468, 0.00017139616829808801, 0.00016649567987769842, 0.00017068763554561883, 0.000004319642357586417 ]
{ "id": 3, "code_window": [ " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n", " <Select\n", " autoFocus={false}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 74 }
// Copyright 2012 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin,race linux,race freebsd,race package unix import ( "runtime" "unsafe" ) const raceenabled = true func raceAcquire(addr unsafe.Pointer) { runtime.RaceAcquire(addr) } func raceReleaseMerge(addr unsafe.Pointer) { runtime.RaceReleaseMerge(addr) } func raceReadRange(addr unsafe.Pointer, len int) { runtime.RaceReadRange(addr, len) } func raceWriteRange(addr unsafe.Pointer, len int) { runtime.RaceWriteRange(addr, len) }
vendor/golang.org/x/sys/unix/race.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017776869935914874, 0.00017452039173804224, 0.0001660816924413666, 0.00017711558029986918, 0.0000048803581194079015 ]
{ "id": 3, "code_window": [ " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n", " <Select\n", " autoFocus={false}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 74 }
package api import ( "testing" "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/auth" . "github.com/smartystreets/goconvey/convey" ) func TestAdminApiEndpoint(t *testing.T) { role := m.ROLE_ADMIN Convey("Given a server admin attempts to remove themself as an admin", t, func() { updateCmd := dtos.AdminUpdateUserPermissionsForm{ IsGrafanaAdmin: false, } bus.AddHandler("test", func(cmd *m.UpdateUserPermissionsCommand) error { return m.ErrLastGrafanaAdmin }) putAdminScenario("When calling PUT on", "/api/admin/users/1/permissions", "/api/admin/users/:id/permissions", role, updateCmd, func(sc *scenarioContext) { sc.fakeReqWithParams("PUT", sc.url, map[string]string{}).exec() So(sc.resp.Code, ShouldEqual, 400) }) }) Convey("When a server admin attempts to logout himself from all devices", t, func() { bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { cmd.Result = &m.User{Id: TestUserID} return nil }) adminLogoutUserScenario("Should not be allowed when calling POST on", "/api/admin/users/1/logout", "/api/admin/users/:id/logout", func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() So(sc.resp.Code, ShouldEqual, 400) }) }) Convey("When a server admin attempts to logout a non-existing user from all devices", t, func() { userId := int64(0) bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { userId = cmd.Id return m.ErrUserNotFound }) adminLogoutUserScenario("Should return not found when calling POST on", "/api/admin/users/200/logout", "/api/admin/users/:id/logout", func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() So(sc.resp.Code, ShouldEqual, 404) So(userId, ShouldEqual, 200) }) }) Convey("When a server admin attempts to revoke an auth token for a non-existing user", t, func() { userId := int64(0) bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { userId = cmd.Id return m.ErrUserNotFound }) cmd := m.RevokeAuthTokenCmd{AuthTokenId: 2} adminRevokeUserAuthTokenScenario("Should return not found when calling POST on", "/api/admin/users/200/revoke-auth-token", "/api/admin/users/:id/revoke-auth-token", cmd, func(sc *scenarioContext) { sc.fakeReqWithParams("POST", sc.url, map[string]string{}).exec() So(sc.resp.Code, ShouldEqual, 404) So(userId, ShouldEqual, 200) }) }) Convey("When a server admin gets auth tokens for a non-existing user", t, func() { userId := int64(0) bus.AddHandler("test", func(cmd *m.GetUserByIdQuery) error { userId = cmd.Id return m.ErrUserNotFound }) adminGetUserAuthTokensScenario("Should return not found when calling GET on", "/api/admin/users/200/auth-tokens", "/api/admin/users/:id/auth-tokens", func(sc *scenarioContext) { sc.fakeReqWithParams("GET", sc.url, map[string]string{}).exec() So(sc.resp.Code, ShouldEqual, 404) So(userId, ShouldEqual, 200) }) }) } func putAdminScenario(desc string, url string, routePattern string, role m.RoleType, cmd dtos.AdminUpdateUserPermissionsForm, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() sc := setupScenarioContext(url) sc.defaultHandler = Wrap(func(c *m.ReqContext) { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID sc.context.OrgRole = role AdminUpdateUserPermissions(c, cmd) }) sc.m.Put(routePattern, sc.defaultHandler) fn(sc) }) } func adminLogoutUserScenario(desc string, url string, routePattern string, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() hs := HTTPServer{ Bus: bus.GetBus(), AuthTokenService: auth.NewFakeUserAuthTokenService(), } sc := setupScenarioContext(url) sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID sc.context.OrgRole = m.ROLE_ADMIN return hs.AdminLogoutUser(c) }) sc.m.Post(routePattern, sc.defaultHandler) fn(sc) }) } func adminRevokeUserAuthTokenScenario(desc string, url string, routePattern string, cmd m.RevokeAuthTokenCmd, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ Bus: bus.GetBus(), AuthTokenService: fakeAuthTokenService, } sc := setupScenarioContext(url) sc.userAuthTokenService = fakeAuthTokenService sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID sc.context.OrgRole = m.ROLE_ADMIN return hs.AdminRevokeUserAuthToken(c, cmd) }) sc.m.Post(routePattern, sc.defaultHandler) fn(sc) }) } func adminGetUserAuthTokensScenario(desc string, url string, routePattern string, fn scenarioFunc) { Convey(desc+" "+url, func() { defer bus.ClearBusHandlers() fakeAuthTokenService := auth.NewFakeUserAuthTokenService() hs := HTTPServer{ Bus: bus.GetBus(), AuthTokenService: fakeAuthTokenService, } sc := setupScenarioContext(url) sc.userAuthTokenService = fakeAuthTokenService sc.defaultHandler = Wrap(func(c *m.ReqContext) Response { sc.context = c sc.context.UserId = TestUserID sc.context.OrgId = TestOrgID sc.context.OrgRole = m.ROLE_ADMIN return hs.AdminGetUserAuthTokens(c) }) sc.m.Get(routePattern, sc.defaultHandler) fn(sc) }) }
pkg/api/admin_users_test.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017391270375810564, 0.00016951520228758454, 0.000160558833158575, 0.00017053876945283264, 0.000003356476554472465 ]
{ "id": 3, "code_window": [ " <Component\n", " featureToggle={false}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n", " <Select\n", " autoFocus={false}\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 74 }
const cwd = process.cwd(); export const changeCwdToGrafanaUi = () => { process.chdir(`${cwd}/packages/grafana-ui`); return process.cwd(); }; export const changeCwdToGrafanaUiDist = () => { process.chdir(`${cwd}/packages/grafana-ui/dist`); }; export const restoreCwd = () => { process.chdir(cwd); };
scripts/cli/utils/cwd.ts
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017185084288939834, 0.0001716134138405323, 0.00017137598479166627, 0.0001716134138405323, 2.3742904886603355e-7 ]
{ "id": 4, "code_window": [ " [email protected]\n", " </td>\n", " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 148 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render team members when sync enabled 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={false} > <td> <div className="gf-form" > <span> Member </span> </div> </td> </Component> <td> <TagBadge count={0} key="LDAP" label="LDAP" onClick={[Function]} removeIcon={false} /> </td> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned off should not render permissions 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={false} > <td> <div className="gf-form" > <Select autoFocus={false} backspaceRemovesValue={true} className="gf-form-select-box__control--menu-right" isClearable={false} isDisabled={false} isLoading={false} isMulti={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} openMenuOnFocus={false} options={ Array [ Object { "description": "Is team member", "label": "Member", "value": 0, }, Object { "description": "Can add/remove permissions, members and delete team.", "label": "Admin", "value": 4, }, ] } value={ Object { "description": "Is team member", "label": "Member", "value": 0, } } width={null} /> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned on should render permissions select if user is team admin 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={true} > <td> <div className="gf-form" > <Select autoFocus={false} backspaceRemovesValue={true} className="gf-form-select-box__control--menu-right" isClearable={false} isDisabled={false} isLoading={false} isMulti={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} openMenuOnFocus={false} options={ Array [ Object { "description": "Is team member", "label": "Member", "value": 0, }, Object { "description": "Can add/remove permissions, members and delete team.", "label": "Admin", "value": 4, }, ] } value={ Object { "description": "Is team member", "label": "Member", "value": 0, } } width={null} /> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> `; exports[`Render when feature toggle editorsCanAdmin is turned on should render span and disable buttons if user is team member 1`] = ` <tr key="1" > <td className="width-4 text-center" > <img className="filter-table__avatar" src="some/url/" /> </td> <td> testUser </td> <td> [email protected] </td> <Component featureToggle={true} > <td> <div className="gf-form" > <span> Member </span> </div> </td> </Component> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> `;
public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.026751983910799026, 0.002877433318644762, 0.0001693962112767622, 0.0003495292039588094, 0.007262602914124727 ]
{ "id": 4, "code_window": [ " [email protected]\n", " </td>\n", " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 148 }
// Node.closest() polyfill if ('Element' in window && !Element.prototype.closest) { Element.prototype.closest = function(this: any, s) { const matches = (this.document || this.ownerDocument).querySelectorAll(s); let el = this; let i; // eslint-disable-next-line do { i = matches.length; // eslint-disable-next-line while (--i >= 0 && matches.item(i) !== el) {} el = el.parentElement; } while (i < 0 && el); return el; }; } export function getPreviousCousin(node, selector) { let sibling = node.parentElement.previousSibling; let el; while (sibling) { el = sibling.querySelector(selector); if (el) { return el; } sibling = sibling.previousSibling; } return undefined; } export function getNextCharacter(global = window) { const selection = global.getSelection(); if (!selection.anchorNode) { return null; } const range = selection.getRangeAt(0); const text = selection.anchorNode.textContent; const offset = range.startOffset; return text.substr(offset, 1); }
public/app/features/explore/utils/dom.ts
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017909590678755194, 0.00017442928219679743, 0.00016783346654847264, 0.00017526629380881786, 0.0000037801573853357695 ]
{ "id": 4, "code_window": [ " [email protected]\n", " </td>\n", " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 148 }
package models type GetDBHealthQuery struct{}
pkg/models/health.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0007410862599499524, 0.0007410862599499524, 0.0007410862599499524, 0.0007410862599499524, 0 ]
{ "id": 4, "code_window": [ " [email protected]\n", " </td>\n", " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 148 }
<page-header model="navModel"></page-header> <div class="page-container page-body"> <div class="panel-container error-container"> <div class="error-column graph-box"> <div class="error-row"> <div class="error-column error-space-between graph-percentage"> <p>100%</p> <p>80%</p> <p>60%</p> <p>40%</p> <p>20%</p> <p>0%</p> </div> <div class="error-column image-box"> <img src="public/img/graph404.svg" width="100%"> <div class="error-row error-space-between"> <p class="graph-text">Then</p> <p class="graph-text">Now</p> </div> </div> </div> </div> <div class="error-column info-box"> <div class="error-row current-box"> <p class="current-text">current</p> </div> <div class="error-row" style="flex: 1"> <i class="fa fa-minus error-minus"></i> <div class="error-column error-space-between error-full-width"> <div class="error-row error-space-between"> <p>Chances you are on the page you are looking for.</p> <p class="left-margin">0%</p> </div> <div> <h3>Sorry for the inconvenience</h3> <p>Please go back to your <a href="{{appSubUrl}}/" class="error-link">home dashboard</a> and try again.</p> <p>If the error persists, seek help on the <a href="https://community.grafana.com" target="_blank" class="error-link">community site</a>.</p> </div> </div> </div> </div> <span class="react-resizable-handle" style="cursor: default"></span> </div> </div>
public/app/partials/error.html
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00018950695812236518, 0.00017241077148355544, 0.0001661585265537724, 0.0001675509411143139, 0.000008778811206866521 ]
{ "id": 5, "code_window": [ " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 222 }
// Jest Snapshot v1, https://goo.gl/fbAQLP exports[`Render should render component 1`] = ` <Page navModel={ Object { "main": Object { "text": "Configuration", }, "node": Object { "text": "Team List", }, } } > <PageContents isLoading={true} /> </Page> `; exports[`Render should render teams table 1`] = ` <Page navModel={ Object { "main": Object { "text": "Configuration", }, "node": Object { "text": "Team List", }, } } > <PageContents isLoading={false} > <div className="page-action-bar" > <div className="gf-form gf-form--grow" > <ForwardRef inputClassName="gf-form-input" labelClassName="gf-form--has-input-icon gf-form--grow" onChange={[Function]} placeholder="Search teams" value="" /> </div> <div className="page-action-bar__spacer" /> <a className="btn btn-primary" href="org/teams/new" > New team </a> </div> <div className="admin-list-table" > <table className="filter-table filter-table--hover form-inline" > <thead> <tr> <th /> <th> Name </th> <th> Email </th> <th> Members </th> <th style={ Object { "width": "1%", } } /> </tr> </thead> <tbody> <tr key="1" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/1" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > test-1 </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > 1 </a> </td> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> <tr key="2" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/2" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/2" > test-2 </a> </td> <td className="link-td" > <a href="org/teams/edit/2" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/2" > 2 </a> </td> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> <tr key="3" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/3" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/3" > test-3 </a> </td> <td className="link-td" > <a href="org/teams/edit/3" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/3" > 3 </a> </td> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> <tr key="4" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/4" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/4" > test-4 </a> </td> <td className="link-td" > <a href="org/teams/edit/4" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/4" > 4 </a> </td> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> <tr key="5" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/5" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/5" > test-5 </a> </td> <td className="link-td" > <a href="org/teams/edit/5" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/5" > 5 </a> </td> <td className="text-right" > <DeleteButton disabled={false} onConfirm={[Function]} /> </td> </tr> </tbody> </table> </div> </PageContents> </Page> `; exports[`Render when feature toggle editorsCanAdmin is turned on and signedin user is a viewer should disable the new team button 1`] = ` <Page navModel={ Object { "main": Object { "text": "Configuration", }, "node": Object { "text": "Team List", }, } } > <PageContents isLoading={false} > <div className="page-action-bar" > <div className="gf-form gf-form--grow" > <ForwardRef inputClassName="gf-form-input" labelClassName="gf-form--has-input-icon gf-form--grow" onChange={[Function]} placeholder="Search teams" value="" /> </div> <div className="page-action-bar__spacer" /> <a className="btn btn-primary disabled" href="org/teams/new" > New team </a> </div> <div className="admin-list-table" > <table className="filter-table filter-table--hover form-inline" > <thead> <tr> <th /> <th> Name </th> <th> Email </th> <th> Members </th> <th style={ Object { "width": "1%", } } /> </tr> </thead> <tbody> <tr key="1" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/1" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > test-1 </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > 1 </a> </td> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> </tbody> </table> </div> </PageContents> </Page> `; exports[`Render when feature toggle editorsCanAdmin is turned on and signedin user is not viewer should enable the new team button 1`] = ` <Page navModel={ Object { "main": Object { "text": "Configuration", }, "node": Object { "text": "Team List", }, } } > <PageContents isLoading={false} > <div className="page-action-bar" > <div className="gf-form gf-form--grow" > <ForwardRef inputClassName="gf-form-input" labelClassName="gf-form--has-input-icon gf-form--grow" onChange={[Function]} placeholder="Search teams" value="" /> </div> <div className="page-action-bar__spacer" /> <a className="btn btn-primary" href="org/teams/new" > New team </a> </div> <div className="admin-list-table" > <table className="filter-table filter-table--hover form-inline" > <thead> <tr> <th /> <th> Name </th> <th> Email </th> <th> Members </th> <th style={ Object { "width": "1%", } } /> </tr> </thead> <tbody> <tr key="1" > <td className="width-4 text-center link-td" > <a href="org/teams/edit/1" > <img className="filter-table__avatar" src="some/url/" /> </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > test-1 </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > [email protected] </a> </td> <td className="link-td" > <a href="org/teams/edit/1" > 1 </a> </td> <td className="text-right" > <DeleteButton disabled={true} onConfirm={[Function]} /> </td> </tr> </tbody> </table> </div> </PageContents> </Page> `;
public/app/features/teams/__snapshots__/TeamList.test.tsx.snap
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.006112234201282263, 0.0005415268242359161, 0.00016258563846349716, 0.0002039157843682915, 0.0010190358152613044 ]
{ "id": 5, "code_window": [ " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 222 }
<div class="gf-form-inline" ng-class="{'gf-form-disabled': agg.hide}"> <div class="gf-form"> <label class="gf-form-label query-keyword width-7"> Metric &nbsp; <a ng-click="toggleShowMetric()" bs-tooltip="'Click to toggle show / hide metric'"> <i class="fa fa-eye" ng-hide="agg.hide"></i> <i class="fa fa-eye-slash" ng-show="agg.hide"></i> </a> </label> </div> <div class="gf-form"> <metric-segment-model property="agg.type" options="metricAggTypes" on-change="onTypeChange()" custom="false" css-class="width-10"></metric-segment-model> <metric-segment-model ng-if="aggDef.requiresField" property="agg.field" get-options="getFieldsInternal()" on-change="onChange()" css-class="width-12"></metric-segment-model> <metric-segment-model ng-if="aggDef.isPipelineAgg && !aggDef.supportsMultipleBucketPaths" property="agg.pipelineAgg" options="pipelineAggOptions" on-change="onChangeInternal()" custom="false" css-class="width-12"></metric-segment-model> </div> <div class="gf-form gf-form--grow" ng-if="aggDef.isPipelineAgg && aggDef.supportsMultipleBucketPaths"> <label class="gf-form-label gf-form-label--grow"> <a ng-click="toggleVariables()"> <i class="fa fa-caret-down" ng-show="showVariables"></i> <i class="fa fa-caret-right" ng-hide="showVariables"></i> {{variablesLinkText}} </a> </label> </div> <div class="gf-form gf-form--grow"> <label class="gf-form-label gf-form-label--grow"> <a ng-click="toggleOptions()" ng-if="settingsLinkText"> <i class="fa fa-caret-down" ng-show="showOptions"></i> <i class="fa fa-caret-right" ng-hide="showOptions"></i> {{settingsLinkText}} </a> </label> </div> <div class="gf-form"> <label class="gf-form-label" ng-if="isFirst"> <a class="pointer" ng-click="addMetricAgg()"><i class="fa fa-plus"></i></a> </label> <label class="gf-form-label" ng-if="!isSingle"> <a class="pointer" ng-click="removeMetricAgg()"><i class="fa fa-minus"></i></a> </label> </div> </div> <div class="gf-form-group" ng-if="showVariables"> <elastic-pipeline-variables variables="agg.pipelineVariables" options="pipelineAggOptions" on-change="onChangeInternal()" /> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10"> Script <info-popover mode="right-normal"> Elasticsearch v5.0 and above: Scripting language is Painless. Use <i>params.&lt;var&gt;</i> to reference a variable.<br/><br/> Elasticsearch pre-v5.0: Scripting language is per default Groovy if not changed. For Groovy use <i>&lt;var&gt;</i> to reference a variable. </info-popover> </label> <input type="text" class="gf-form-input max-width-24" empty-to-null ng-model="agg.settings.script" ng-blur="onChangeInternal()" spellcheck='false' placeholder="params.var1 / params.var2"> </div> </div> <div class="gf-form-group" ng-if="showOptions"> <div class="gf-form offset-width-7" ng-if="agg.type === 'derivative'"> <label class="gf-form-label width-10">Unit</label> <input type="text" class="gf-form-input max-width-12" ng-model="agg.settings.unit" ng-blur="onChangeInternal()" spellcheck='false'> </div> <div ng-if="agg.type === 'moving_avg'"> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Model</label> <metric-segment-model property="agg.settings.model" options="movingAvgModelTypes" on-change="onChangeClearInternal()" custom="false" css-class="width-12"></metric-segment-model> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Window</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.window" ng-blur="onChangeInternal()" spellcheck='false'> </div> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Predict</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.predict" ng-blur="onChangeInternal()" spellcheck='false'> </div> <div class="gf-form offset-width-7" ng-repeat="setting in modelSettings"> <label class="gf-form-label width-10">{{setting.text}}</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.settings[setting.value]" ng-blur="onChangeInternal()" spellcheck='false'> </div> <gf-form-switch ng-if="agg.settings.model == 'holt_winters'" class="gf-form offset-width-7" label="Pad" label-class="width-10" checked="agg.settings.settings.pad" on-change="onChangeInternal()"></gf-form-switch> <gf-form-switch ng-if="agg.settings.model.match('ewma|holt_winters|holt') !== null" class="gf-form offset-width-7" label="Minimize" label-class="width-10" checked="agg.settings.minimize" on-change="onChangeInternal()"></gf-form-switch> </div> <div class="gf-form offset-width-7" ng-if="agg.type === 'percentiles'"> <label class="gf-form-label width-10">Percentiles</label> <input type="text" class="gf-form-input max-width-12" ng-model="agg.settings.percents" array-join ng-blur="onChange()"></input> </div> <div class="gf-form offset-width-7" ng-if="agg.type === 'raw_document'"> <label class="gf-form-label width-10">Size</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.size" ng-blur="onChange()"></input> </div> <div class="gf-form offset-width-7" ng-if="agg.type === 'cardinality'"> <label class="gf-form-label width-10">Precision threshold</label> <input type="number" class="gf-form-input max-width-12" ng-model="agg.settings.precision_threshold" ng-blur="onChange()"></input> </div> <div ng-if="agg.type === 'extended_stats'"> <gf-form-switch ng-repeat="stat in extendedStats" class="gf-form offset-width-7" label="{{stat.text}}" label-class="width-10" checked="agg.meta[stat.value]" on-change="onChangeInternal()"></gf-form-switch> <div class="gf-form offset-width-7"> <label class="gf-form-label width-10">Sigma</label> <input type="number" class="gf-form-input max-width-12" placeholder="3" ng-model="agg.settings.sigma" ng-blur="onChange()"></input> </div> </div> <div class="gf-form offset-width-7" ng-if="aggDef.supportsInlineScript"> <label class="gf-form-label width-10">Script</label> <input type="text" class="gf-form-input max-width-12" empty-to-null ng-model="agg.inlineScript" ng-blur="onChangeInternal()" spellcheck='false' placeholder="_value * 1"> </div> <div class="gf-form offset-width-7" ng-if="aggDef.supportsMissing"> <label class="gf-form-label width-10"> Missing <tip>The missing parameter defines how documents that are missing a value should be treated. By default they will be ignored but it is also possible to treat them as if they had a value</tip> </label> <input type="number" class="gf-form-input max-width-12" empty-to-null ng-model="agg.settings.missing" ng-blur="onChangeInternal()" spellcheck='false'> </div> </div>
public/app/plugins/datasource/elasticsearch/partials/metric_agg.html
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.010413127951323986, 0.0013985205441713333, 0.0001668631302891299, 0.0002932298230007291, 0.002850156743079424 ]
{ "id": 5, "code_window": [ " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 222 }
scripts/build/release_publisher/testdata/grafana-enterprise_5.4.0-123pre1_amd64.deb
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00017859830404631793, 0.00017859830404631793, 0.00017859830404631793, 0.00017859830404631793, 0 ]
{ "id": 5, "code_window": [ " <Component\n", " featureToggle={true}\n", " >\n", " <td>\n", " <div\n", " className=\"gf-form\"\n", " >\n" ], "labels": [ "keep", "keep", "keep", "replace", "keep", "keep", "keep" ], "after_edit": [ " <td\n", " className=\"width-5 team-permissions\"\n", " >\n" ], "file_path": "public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap", "type": "replace", "edit_start_line_idx": 222 }
apiVersion: 1 datasources: - name: name type: type access: proxy orgId: 2 url: url password: password user: user database: database basicAuth: true basicAuthUser: basic_auth_user basicAuthPassword: basic_auth_password withCredentials: true isDefault: true jsonData: graphiteVersion: "1.1" tlsAuth: true tlsAuthWithCACert: true secureJsonData: tlsCACert: "MjNOcW9RdkbUDHZmpco2HCYzVq9dE+i6Yi+gmUJotq5CDA==" tlsClientCert: "ckN0dGlyMXN503YNfjTcf9CV+GGQneN+xmAclQ==" tlsClientKey: "ZkN4aG1aNkja/gKAB1wlnKFIsy2SRDq4slrM0A==" editable: true version: 10 deleteDatasources: - name: old-graphite3 orgId: 2
pkg/services/provisioning/datasources/testdata/all-properties/all-properties.yaml
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0001785981294233352, 0.00017103273421525955, 0.00016277939721476287, 0.00017137668328359723, 0.000005637565209326567 ]
{ "id": 6, "code_window": [ " padding-left: 10px;\n", " margin-bottom: 5px;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", ".admin-list-table {\n", " .team-permissions {\n", " padding-right: 120px;\n", " }\n", "}" ], "file_path": "public/sass/pages/_admin.scss", "type": "add", "edit_start_line_idx": 21 }
import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { DeleteButton, Select, SelectOptionItem } from '@grafana/ui'; import { TeamMember, teamsPermissionLevels } from 'app/types'; import { WithFeatureToggle } from 'app/core/components/WithFeatureToggle'; import { updateTeamMember, removeTeamMember } from './state/actions'; import { TagBadge } from 'app/core/components/TagFilter/TagBadge'; export interface Props { member: TeamMember; syncEnabled: boolean; editorsCanAdmin: boolean; signedInUserIsTeamAdmin: boolean; removeTeamMember?: typeof removeTeamMember; updateTeamMember?: typeof updateTeamMember; } export class TeamMemberRow extends PureComponent<Props> { constructor(props: Props) { super(props); this.renderLabels = this.renderLabels.bind(this); this.renderPermissions = this.renderPermissions.bind(this); } onRemoveMember(member: TeamMember) { this.props.removeTeamMember(member.userId); } onPermissionChange = (item: SelectOptionItem, member: TeamMember) => { const permission = item.value; const updatedTeamMember = { ...member, permission }; this.props.updateTeamMember(updatedTeamMember); }; renderPermissions(member: TeamMember) { const { editorsCanAdmin, signedInUserIsTeamAdmin } = this.props; const value = teamsPermissionLevels.find(dp => dp.value === member.permission); return ( <WithFeatureToggle featureToggle={editorsCanAdmin}> <td> <div className="gf-form"> {signedInUserIsTeamAdmin && ( <Select isSearchable={false} options={teamsPermissionLevels} onChange={item => this.onPermissionChange(item, member)} className="gf-form-select-box__control--menu-right" value={value} /> )} {!signedInUserIsTeamAdmin && <span>{value.label}</span>} </div> </td> </WithFeatureToggle> ); } renderLabels(labels: string[]) { if (!labels) { return <td />; } return ( <td> {labels.map(label => ( <TagBadge key={label} label={label} removeIcon={false} count={0} onClick={() => {}} /> ))} </td> ); } render() { const { member, syncEnabled, signedInUserIsTeamAdmin } = this.props; return ( <tr key={member.userId}> <td className="width-4 text-center"> <img className="filter-table__avatar" src={member.avatarUrl} /> </td> <td>{member.login}</td> <td>{member.email}</td> {this.renderPermissions(member)} {syncEnabled && this.renderLabels(member.labels)} <td className="text-right"> <DeleteButton onConfirm={() => this.onRemoveMember(member)} disabled={!signedInUserIsTeamAdmin} /> </td> </tr> ); } } function mapStateToProps(state) { return {}; } const mapDispatchToProps = { removeTeamMember, updateTeamMember, }; export default connect( mapStateToProps, mapDispatchToProps )(TeamMemberRow);
public/app/features/teams/TeamMemberRow.tsx
1
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0007163033587858081, 0.0002198746078647673, 0.0001656868844293058, 0.00016952920123003423, 0.00015704781981185079 ]
{ "id": 6, "code_window": [ " padding-left: 10px;\n", " margin-bottom: 5px;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", ".admin-list-table {\n", " .team-permissions {\n", " padding-right: 120px;\n", " }\n", "}" ], "file_path": "public/sass/pages/_admin.scss", "type": "add", "edit_start_line_idx": 21 }
package shareddefaults import ( "os" "path/filepath" "runtime" ) // SharedCredentialsFilename returns the SDK's default file path // for the shared credentials file. // // Builds the shared config file path based on the OS's platform. // // - Linux/Unix: $HOME/.aws/credentials // - Windows: %USERPROFILE%\.aws\credentials func SharedCredentialsFilename() string { return filepath.Join(UserHomeDir(), ".aws", "credentials") } // SharedConfigFilename returns the SDK's default file path for // the shared config file. // // Builds the shared config file path based on the OS's platform. // // - Linux/Unix: $HOME/.aws/config // - Windows: %USERPROFILE%\.aws\config func SharedConfigFilename() string { return filepath.Join(UserHomeDir(), ".aws", "config") } // UserHomeDir returns the home directory for the user the process is // running under. func UserHomeDir() string { if runtime.GOOS == "windows" { // Windows return os.Getenv("USERPROFILE") } // *nix return os.Getenv("HOME") }
vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.0003088261291850358, 0.0001990714081330225, 0.0001681488793110475, 0.00017019356891978532, 0.000055018779676174745 ]
{ "id": 6, "code_window": [ " padding-left: 10px;\n", " margin-bottom: 5px;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", ".admin-list-table {\n", " .team-permissions {\n", " padding-right: 120px;\n", " }\n", "}" ], "file_path": "public/sass/pages/_admin.scss", "type": "add", "edit_start_line_idx": 21 }
package usagestats import ( "bytes" "io/ioutil" "runtime" "sync" "testing" "time" "net/http" "net/http/httptest" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/setting" . "github.com/smartystreets/goconvey/convey" ) func TestMetrics(t *testing.T) { Convey("Test send usage stats", t, func() { uss := &UsageStatsService{ Bus: bus.New(), SQLStore: sqlstore.InitTestDB(t), } var getSystemStatsQuery *models.GetSystemStatsQuery uss.Bus.AddHandler(func(query *models.GetSystemStatsQuery) error { query.Result = &models.SystemStats{ Dashboards: 1, Datasources: 2, Users: 3, ActiveUsers: 4, Orgs: 5, Playlists: 6, Alerts: 7, Stars: 8, Folders: 9, DashboardPermissions: 10, FolderPermissions: 11, ProvisionedDashboards: 12, Snapshots: 13, Teams: 14, AuthTokens: 15, } getSystemStatsQuery = query return nil }) var getDataSourceStatsQuery *models.GetDataSourceStatsQuery uss.Bus.AddHandler(func(query *models.GetDataSourceStatsQuery) error { query.Result = []*models.DataSourceStats{ { Type: models.DS_ES, Count: 9, }, { Type: models.DS_PROMETHEUS, Count: 10, }, { Type: "unknown_ds", Count: 11, }, { Type: "unknown_ds2", Count: 12, }, } getDataSourceStatsQuery = query return nil }) var getDataSourceAccessStatsQuery *models.GetDataSourceAccessStatsQuery uss.Bus.AddHandler(func(query *models.GetDataSourceAccessStatsQuery) error { query.Result = []*models.DataSourceAccessStats{ { Type: models.DS_ES, Access: "direct", Count: 1, }, { Type: models.DS_ES, Access: "proxy", Count: 2, }, { Type: models.DS_PROMETHEUS, Access: "proxy", Count: 3, }, { Type: "unknown_ds", Access: "proxy", Count: 4, }, { Type: "unknown_ds2", Access: "", Count: 5, }, { Type: "unknown_ds3", Access: "direct", Count: 6, }, { Type: "unknown_ds4", Access: "direct", Count: 7, }, { Type: "unknown_ds5", Access: "proxy", Count: 8, }, } getDataSourceAccessStatsQuery = query return nil }) var getAlertNotifierUsageStatsQuery *models.GetAlertNotifierUsageStatsQuery uss.Bus.AddHandler(func(query *models.GetAlertNotifierUsageStatsQuery) error { query.Result = []*models.NotifierUsageStats{ { Type: "slack", Count: 1, }, { Type: "webhook", Count: 2, }, } getAlertNotifierUsageStatsQuery = query return nil }) var wg sync.WaitGroup var responseBuffer *bytes.Buffer var req *http.Request ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { req = r buf, err := ioutil.ReadAll(r.Body) if err != nil { t.Fatalf("Failed to read response body, err=%v", err) } responseBuffer = bytes.NewBuffer(buf) wg.Done() })) usageStatsURL = ts.URL oauthProviders := map[string]bool{ "github": true, "gitlab": true, "google": true, "generic_oauth": true, "grafana_com": true, } uss.sendUsageStats(oauthProviders) Convey("Given reporting not enabled and sending usage stats", func() { setting.ReportingEnabled = false uss.sendUsageStats(oauthProviders) Convey("Should not gather stats or call http endpoint", func() { So(getSystemStatsQuery, ShouldBeNil) So(getDataSourceStatsQuery, ShouldBeNil) So(getDataSourceAccessStatsQuery, ShouldBeNil) So(req, ShouldBeNil) }) }) Convey("Given reporting enabled and sending usage stats", func() { setting.ReportingEnabled = true setting.BuildVersion = "5.0.0" setting.AnonymousEnabled = true setting.BasicAuthEnabled = true setting.LdapEnabled = true setting.AuthProxyEnabled = true setting.Packaging = "deb" wg.Add(1) uss.sendUsageStats(oauthProviders) Convey("Should gather stats and call http endpoint", func() { if waitTimeout(&wg, 2*time.Second) { t.Fatalf("Timed out waiting for http request") } So(getSystemStatsQuery, ShouldNotBeNil) So(getDataSourceStatsQuery, ShouldNotBeNil) So(getDataSourceAccessStatsQuery, ShouldNotBeNil) So(getAlertNotifierUsageStatsQuery, ShouldNotBeNil) So(req, ShouldNotBeNil) So(req.Method, ShouldEqual, http.MethodPost) So(req.Header.Get("Content-Type"), ShouldEqual, "application/json") So(responseBuffer, ShouldNotBeNil) j, err := simplejson.NewFromReader(responseBuffer) So(err, ShouldBeNil) So(j.Get("version").MustString(), ShouldEqual, "5_0_0") So(j.Get("os").MustString(), ShouldEqual, runtime.GOOS) So(j.Get("arch").MustString(), ShouldEqual, runtime.GOARCH) metrics := j.Get("metrics") So(metrics.Get("stats.dashboards.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Dashboards) So(metrics.Get("stats.users.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Users) So(metrics.Get("stats.orgs.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Orgs) So(metrics.Get("stats.playlist.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Playlists) So(metrics.Get("stats.plugins.apps.count").MustInt(), ShouldEqual, len(plugins.Apps)) So(metrics.Get("stats.plugins.panels.count").MustInt(), ShouldEqual, len(plugins.Panels)) So(metrics.Get("stats.plugins.datasources.count").MustInt(), ShouldEqual, len(plugins.DataSources)) So(metrics.Get("stats.alerts.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Alerts) So(metrics.Get("stats.active_users.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.ActiveUsers) So(metrics.Get("stats.datasources.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Datasources) So(metrics.Get("stats.stars.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Stars) So(metrics.Get("stats.folders.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Folders) So(metrics.Get("stats.dashboard_permissions.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.DashboardPermissions) So(metrics.Get("stats.folder_permissions.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.FolderPermissions) So(metrics.Get("stats.provisioned_dashboards.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.ProvisionedDashboards) So(metrics.Get("stats.snapshots.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Snapshots) So(metrics.Get("stats.teams.count").MustInt(), ShouldEqual, getSystemStatsQuery.Result.Teams) So(metrics.Get("stats.total_auth_token.count").MustInt64(), ShouldEqual, 15) So(metrics.Get("stats.avg_auth_token_per_user.count").MustInt64(), ShouldEqual, 5) So(metrics.Get("stats.ds."+models.DS_ES+".count").MustInt(), ShouldEqual, 9) So(metrics.Get("stats.ds."+models.DS_PROMETHEUS+".count").MustInt(), ShouldEqual, 10) So(metrics.Get("stats.ds.other.count").MustInt(), ShouldEqual, 11+12) So(metrics.Get("stats.ds_access."+models.DS_ES+".direct.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.ds_access."+models.DS_ES+".proxy.count").MustInt(), ShouldEqual, 2) So(metrics.Get("stats.ds_access."+models.DS_PROMETHEUS+".proxy.count").MustInt(), ShouldEqual, 3) So(metrics.Get("stats.ds_access.other.direct.count").MustInt(), ShouldEqual, 6+7) So(metrics.Get("stats.ds_access.other.proxy.count").MustInt(), ShouldEqual, 4+8) So(metrics.Get("stats.alert_notifiers.slack.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.alert_notifiers.webhook.count").MustInt(), ShouldEqual, 2) So(metrics.Get("stats.auth_enabled.anonymous.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.basic_auth.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.ldap.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.auth_proxy.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.oauth_github.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.oauth_gitlab.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.oauth_google.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.oauth_generic_oauth.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.auth_enabled.oauth_grafana_com.count").MustInt(), ShouldEqual, 1) So(metrics.Get("stats.packaging.deb.count").MustInt(), ShouldEqual, 1) }) }) Reset(func() { ts.Close() }) }) } func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool { c := make(chan struct{}) go func() { defer close(c) wg.Wait() }() select { case <-c: return false // completed normally case <-time.After(timeout): return true // timed out } }
pkg/infra/usagestats/usage_stats_test.go
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.00019225463620387018, 0.0001697414118098095, 0.0001640759001020342, 0.00016861224139574915, 0.00000513143004354788 ]
{ "id": 6, "code_window": [ " padding-left: 10px;\n", " margin-bottom: 5px;\n", " }\n", "}\n" ], "labels": [ "keep", "keep", "keep", "add" ], "after_edit": [ "\n", ".admin-list-table {\n", " .team-permissions {\n", " padding-right: 120px;\n", " }\n", "}" ], "file_path": "public/sass/pages/_admin.scss", "type": "add", "edit_start_line_idx": 21 }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width" /> <style>body { width: 100% !important; min-width: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; margin: 0; padding: 0; } img { outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; width: auto; float: left; clear: both; display: block; } body { color: #222222; font-family: "Helvetica", "Arial", sans-serif; font-weight: normal; padding: 0; margin: 0; text-align: left; line-height: 1.3; } body { font-size: 14px; line-height: 19px; } a:hover { color: #2795b6 !important; } a:active { color: #2795b6 !important; } a:visited { color: #2ba6cb !important; } body { font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; } a:hover { color: #ff8f2b !important; } a:active { color: #F2821E !important; } a:visited { color: #E67612 !important; } .better-button:hover a { color: #FFFFFF !important; background-color: #F2821E; border: 1px solid #F2821E; } .better-button:visited a { color: #FFFFFF !important; } .better-button:active a { color: #FFFFFF !important; } .better-button-alt:hover a { color: #ff8f2b !important; background-color: #DDDDDD; border: 1px solid #F2821E; } .better-button-alt:visited a { color: #ff8f2b !important; } .better-button-alt:active a { color: #ff8f2b !important; } body { height: 100% !important; width: 100% !important; } body .copy { -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } .ExternalClass { width: 100%; } .ExternalClass { line-height: 100%; } img { -ms-interpolation-mode: bicubic; } img { border: 0 !important; outline: none !important; text-decoration: none !important; } a:hover { text-decoration: underline; } @media only screen and (max-width: 600px) { table[class="body"] center { min-width: 0 !important; } table[class="body"] .container { width: 95% !important; } table[class="body"] .row { width: 100% !important; display: block !important; } table[class="body"] .wrapper { display: block !important; padding-right: 0 !important; } table[class="body"] .columns { table-layout: fixed !important; float: none !important; width: 100% !important; padding-right: 0px !important; padding-left: 0px !important; display: block !important; } table[class="body"] table.columns td { width: 100% !important; } table[class="body"] .columns td.six { width: 50% !important; } table[class="body"] .columns td.twelve { width: 100% !important; } table[class="body"] table.columns td.expander { width: 1px !important; } .logo { margin-left: 10px; } } @media (max-width: 600px) { table[class="email-container"] { width: 95% !important; } img[class="fluid"] { width: 100% !important; max-width: 100% !important; height: auto !important; margin: auto !important; } img[class="fluid-centered"] { width: 100% !important; max-width: 100% !important; height: auto !important; margin: auto !important; } img[class="fluid-centered"] { margin: auto !important; } td[class="comms-content"] { padding: 20px !important; } td[class="stack-column"] { display: block !important; width: 100% !important; direction: ltr !important; } td[class="stack-column-center"] { display: block !important; width: 100% !important; direction: ltr !important; } td[class="stack-column-center"] { text-align: center !important; } td[class="copy"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="copy -center"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="copy -bold"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="small-text"] { font-size: 14px !important; line-height: 24px !important; padding: 0 30px !important; } td[class="mini-centered-text"] { font-size: 14px !important; line-height: 24px !important; padding: 15px 30px !important; } td[class="copy -padd"] { padding: 0 40px !important; } span[class="sep"] { display: none !important; } td[class="mb-hide"] { display: none !important; height: 0 !important; } td[class="spacer mb-shorten"] { height: 25px !important; } .two-up td { width: 270px; } } </style></head> <body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" class="main" style="height: 100% !important; width: 100% !important; min-width: 100%; -webkit-text-size-adjust: none; -ms-text-size-adjust: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; text-align: left; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; margin: 0 auto; padding: 0;" bgcolor="#2e2e2e"> <table class="body" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; height: 100%; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" bgcolor="#2e2e2e"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" align="center" valign="top" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;"> <center style="width: 100%; min-width: 580px;"> <table class="row header" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; margin-top: 25px; margin-bottom: 25px; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" align="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" valign="top"> <center style="width: 100%; min-width: 580px;"> <table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="twelve sub-columns center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; min-width: 0px; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 10px 10px 0px;" align="center" valign="top"> <img class="logo" src="http://grafana.org/assets/img/logo_new_transparent_200x48.png" style="width: 200px; display: inline; outline: none !important; text-decoration: none !important; -ms-interpolation-mode: bicubic; clear: both; border: 0;" align="none" /> </td> <td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td> </tr> </table> </td> </tr> </table> </center> </td> </tr> </table> <table class="container" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: inherit; width: 580px; margin: 0 auto; padding: 0;" width="600" bgcolor="#efefef"> <tr style="vertical-align: top; padding: 0;" align="left"> <td height="2" class="spacer mb-shorten" style="font-size: 0; line-height: 0; mso-table-lspace: 0pt; mso-table-rspace: 0pt; background-image: linear-gradient(to right, #ffed00 0%, #f26529 75%); height: 2px !important; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0; border: 0;" valign="top" align="left"> </td> </tr> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="mini-centered-text" style="color: #343b41; mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 25px 35px; font: 400 16px/27px 'Helvetica Neue', Helvetica, Arial, sans-serif;" align="center" valign="top"> {{Subject .Subject "{{.Title}}"}} <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <h3 style="/*text-align: center*/; color: {{.SeverityColor}}; font-weight: bold; font-style: italic; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.3; word-break: normal; font-size: 22px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 10px 0; padding: 0;" align="left">{{.Title}}</h3> </td> </tr> </table> </td> </tr> </table> <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0 0px 0 0;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <p style="/*text-align: center*/; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="left">{{.Message}}</p> </td> </tr> </table> </td> </tr> </table> {{if ne .Error "" }} <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0 0px 0 0;" align="left" valign="top"> <center style="width: 100%; min-width: 580px;"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="twelve last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="left" valign="top"> <h5 style="font-weight: bold; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.3; word-break: normal; font-size: 18px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left">Error message</h5> </td> </tr> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="twelve last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="left" valign="top"> <p style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="left">{{.Error}}</p> </td> </tr> </table> </center> </td> </tr> </table> {{end}} {{if ne .State "ok" }} <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0 0px 0 0;" align="left" valign="top"> <center style="width: 100%; min-width: 580px;"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="six" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 50%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="left" valign="top"> <h5 style="font-weight: bold; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.3; word-break: normal; font-size: 18px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left">Metric name</h5> </td> <td class="six last" style="width: 100px; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="right" valign="top"> <h5 style="font-weight: bold; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; line-height: 1.3; word-break: normal; font-size: 18px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="right">Value</h5> </td> </tr> {{range .EvalMatches}} <tr style="vertical-align: top; padding: 0;" align="left"> <td class="six" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 50%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="left" valign="top"> <h5 class="data" style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 1.3; word-break: normal; font-size: 16px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left">{{.Metric}}</h5> </td> <td class="six last" style="width: 100px; word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="right" valign="top"> <h5 class="data" style="color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 1.3; word-break: normal; font-size: 16px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="right">{{.Value}}</h5> </td> </tr> {{end}} </table> </center> </td> </tr> </table> {{end}} <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> {{if ne .ImageLink "" }} <img src="{{.ImageLink}}" alt="Alerting Panel" style="outline: none !important; text-decoration: none !important; -ms-interpolation-mode: bicubic; width: auto; clear: both; display: block; border: 0;" align="left" /> {{end}} {{if ne .EmbededImage "" }} <img src="cid:{{.EmbededImage}}" alt="Alerting Panel" style="outline: none !important; text-decoration: none !important; -ms-interpolation-mode: bicubic; width: auto; clear: both; display: block; border: 0;" align="left" /> {{end}} </td> </tr> </table> </td> </tr> </table> <table class="row" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 100%; position: relative; display: block; padding: 0px;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 0px 0px;" align="left" valign="top"> <table class="twelve columns" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="center six" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 50%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <table class="better-button" align="center" border="0" cellspacing="0" cellpadding="0" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; margin-top: 10px; margin-bottom: 20px; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td align="center" class="better-button" bgcolor="#ff8f2b" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; margin: 0; padding: 0px;" valign="top"> <a href="{{.RuleUrl}}" target="_blank" style="color: #FFF; text-decoration: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; padding: 12px 25px; border: 1px solid #ff8f2b;">View your Alert rule</a> </td> </tr> </table> </td> <td class="center six" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 50%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" align="center" valign="top"> <table class="better-button" align="center" border="0" cellspacing="0" cellpadding="0" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: left; margin-top: 10px; margin-bottom: 20px; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td align="center" class="better-button-alt" bgcolor="#efefef" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; margin: 0; padding: 0px;" valign="top"> <a href="{{.AlertPageUrl}}" target="_blank" style="color: #ff8f2b; text-decoration: none; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; background-color: #EFEFEF; padding: 12px 25px; border: 1px solid #ff8f2b;"> Go to the Alerts page</a> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> </td> </tr> </table> <table class="footer center" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: center; color: #999999; margin-top: 20px; padding: 0;" bgcolor="#2e2e2e"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="wrapper last" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; position: relative; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 10px 20px 0px 0px;" align="left" valign="top"> <table class="twelve columns center" style="border-spacing: 0; border-collapse: collapse; vertical-align: top; text-align: center; width: 580px; margin: 0 auto; padding: 0;"> <tr style="vertical-align: top; padding: 0;" align="left"> <td class="twelve" align="center" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; width: 100%; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0px 0px 10px;" valign="top"> <center style="width: 100%; min-width: 580px;"> <p style="font-size: 12px; color: #999999; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0 0 10px; padding: 0;" align="center"> Sent by <a href="{{.AppUrl}}" style="color: #E67612; text-decoration: none;">Grafana v{{.BuildVersion}}</a> <br />© 2016 Grafana and raintank </p> </center> </td> <td class="expander" style="word-break: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; border-collapse: collapse !important; visibility: hidden; width: 0px; color: #222222; font-family: 'Open Sans', 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; font-weight: normal; line-height: 19px; font-size: 14px; -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: none; margin: 0; padding: 0;" align="left" valign="top"></td> </tr> </table> </td> </tr> </table> </center> </td> </tr> </table> </body> </html>
public/emails/alert_notification.html
0
https://github.com/grafana/grafana/commit/e23e6a8bdc1c5c4addbdf4bf76334fcb17b901a2
[ 0.020893530920147896, 0.0023828018456697464, 0.00016616214998066425, 0.0003147029201500118, 0.004468369297683239 ]
{ "id": 0, "code_window": [ "\tcursor: default;\n", "\t-webkit-app-region: no-drag;\n", "\tzoom: 1;\n", "\twhite-space: nowrap;\n", "}\n", "\n", ".monaco-workbench .menubar .menubar-menu-items-holder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css", "type": "add", "edit_start_line_idx": 185 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as browser from 'vs/base/browser/browser'; import * as strings from 'vs/base/common/strings'; import { IMenubarMenu, IMenubarMenuItemAction, IMenubarMenuItemSubmenu, IMenubarKeybinding, IMenubarService, IMenubarData } from 'vs/platform/menubar/common/menubar'; import { IMenuService, MenuId, IMenu, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { registerThemingParticipant, ITheme, ICssStyleCollector, IThemeService } from 'vs/platform/theme/common/themeService'; import { IWindowService, MenuBarVisibility, IWindowsService, getTitleBarStyle } from 'vs/platform/windows/common/windows'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ActionRunner, IActionRunner, IAction, Action } from 'vs/base/common/actions'; import { Separator } from 'vs/base/browser/ui/actionbar/actionbar'; import * as DOM from 'vs/base/browser/dom'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { isMacintosh, isLinux } from 'vs/base/common/platform'; import { Menu, IMenuOptions, SubmenuAction, MENU_MNEMONIC_REGEX, cleanMnemonic, MENU_ESCAPED_MNEMONIC_REGEX } from 'vs/base/browser/ui/menu/menu'; import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { Event, Emitter } from 'vs/base/common/event'; import { IDisposable, Disposable, dispose } from 'vs/base/common/lifecycle'; import { domEvent } from 'vs/base/browser/event'; import { IRecentlyOpened } from 'vs/platform/history/common/history'; import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces'; import { RunOnceScheduler } from 'vs/base/common/async'; import { MENUBAR_SELECTION_FOREGROUND, MENUBAR_SELECTION_BACKGROUND, MENUBAR_SELECTION_BORDER, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND } from 'vs/workbench/common/theme'; import { URI } from 'vs/base/common/uri'; import { ILabelService } from 'vs/platform/label/common/label'; import { IUpdateService, StateType } from 'vs/platform/update/common/update'; import { Gesture, EventType, GestureEvent } from 'vs/base/browser/touch'; import { attachMenuStyler } from 'vs/platform/theme/common/styler'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; const $ = DOM.$; interface CustomMenu { title: string; buttonElement: HTMLElement; titleElement: HTMLElement; actions?: IAction[]; } enum MenubarState { HIDDEN, VISIBLE, FOCUSED, OPEN } export class MenubarControl extends Disposable { private keys = [ 'files.autoSave', 'window.menuBarVisibility', 'editor.multiCursorModifier', 'workbench.sideBar.location', 'workbench.statusBar.visible', 'workbench.activityBar.visible', 'window.enableMenuBarMnemonics', 'window.nativeTabs' ]; private topLevelMenus: { 'File': IMenu; 'Edit': IMenu; 'Selection': IMenu; 'View': IMenu; 'Go': IMenu; 'Debug': IMenu; 'Terminal': IMenu; 'Window'?: IMenu; 'Help': IMenu; [index: string]: IMenu; }; private topLevelTitles = { 'File': nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File"), 'Edit': nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit"), 'Selection': nls.localize({ key: 'mSelection', comment: ['&& denotes a mnemonic'] }, "&&Selection"), 'View': nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View"), 'Go': nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go"), 'Debug': nls.localize({ key: 'mDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"), 'Terminal': nls.localize({ key: 'mTerminal', comment: ['&& denotes a mnemonic'] }, "&&Terminal"), 'Help': nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help") }; private focusedMenu: { index: number; holder?: HTMLElement; widget?: Menu; }; private customMenus: CustomMenu[]; private menuUpdater: RunOnceScheduler; private actionRunner: IActionRunner; private focusToReturn: HTMLElement; private container: HTMLElement; private recentlyOpened: IRecentlyOpened; private updatePending: boolean; private _focusState: MenubarState; // Input-related private _mnemonicsInUse: boolean; private openedViaKeyboard: boolean; private awaitingAltRelease: boolean; private ignoreNextMouseUp: boolean; private mnemonics: Map<KeyCode, number>; private _onVisibilityChange: Emitter<boolean>; private _onFocusStateChange: Emitter<boolean>; private static MAX_MENU_RECENT_ENTRIES = 10; constructor( @IThemeService private themeService: IThemeService, @IMenubarService private menubarService: IMenubarService, @IMenuService private menuService: IMenuService, @IWindowService private windowService: IWindowService, @IWindowsService private windowsService: IWindowsService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IConfigurationService private configurationService: IConfigurationService, @ILabelService private labelService: ILabelService, @IUpdateService private updateService: IUpdateService, @IStorageService private storageService: IStorageService, @INotificationService private notificationService: INotificationService, @IPreferencesService private preferencesService: IPreferencesService, @IEnvironmentService private environmentService: IEnvironmentService ) { super(); this.topLevelMenus = { 'File': this._register(this.menuService.createMenu(MenuId.MenubarFileMenu, this.contextKeyService)), 'Edit': this._register(this.menuService.createMenu(MenuId.MenubarEditMenu, this.contextKeyService)), 'Selection': this._register(this.menuService.createMenu(MenuId.MenubarSelectionMenu, this.contextKeyService)), 'View': this._register(this.menuService.createMenu(MenuId.MenubarViewMenu, this.contextKeyService)), 'Go': this._register(this.menuService.createMenu(MenuId.MenubarGoMenu, this.contextKeyService)), 'Debug': this._register(this.menuService.createMenu(MenuId.MenubarDebugMenu, this.contextKeyService)), 'Terminal': this._register(this.menuService.createMenu(MenuId.MenubarTerminalMenu, this.contextKeyService)), 'Help': this._register(this.menuService.createMenu(MenuId.MenubarHelpMenu, this.contextKeyService)) }; if (isMacintosh) { this.topLevelMenus['Preferences'] = this._register(this.menuService.createMenu(MenuId.MenubarPreferencesMenu, this.contextKeyService)); } this.menuUpdater = this._register(new RunOnceScheduler(() => this.doSetupMenubar(), 200)); this.actionRunner = this._register(new ActionRunner()); this._register(this.actionRunner.onDidBeforeRun(() => { this.setUnfocusedState(); })); this._onVisibilityChange = this._register(new Emitter<boolean>()); this._onFocusStateChange = this._register(new Emitter<boolean>()); if (isMacintosh || this.currentTitlebarStyleSetting !== 'custom') { for (let topLevelMenuName of Object.keys(this.topLevelMenus)) { this._register(this.topLevelMenus[topLevelMenuName].onDidChange(() => this.setupMenubar())); } this.doSetupMenubar(); } this._focusState = MenubarState.HIDDEN; this.windowService.getRecentlyOpened().then((recentlyOpened) => { this.recentlyOpened = recentlyOpened; }); this.detectAndRecommendCustomTitlebar(); this.registerListeners(); } private get currentEnableMenuBarMnemonics(): boolean { let enableMenuBarMnemonics = this.configurationService.getValue<boolean>('window.enableMenuBarMnemonics'); if (typeof enableMenuBarMnemonics !== 'boolean') { enableMenuBarMnemonics = true; } return enableMenuBarMnemonics; } private get currentSidebarPosition(): string { return this.configurationService.getValue<string>('workbench.sideBar.location'); } private get currentStatusBarVisibility(): boolean { let setting = this.configurationService.getValue<boolean>('workbench.statusBar.visible'); if (typeof setting !== 'boolean') { setting = true; } return setting; } private get currentActivityBarVisibility(): boolean { let setting = this.configurationService.getValue<boolean>('workbench.activityBar.visible'); if (typeof setting !== 'boolean') { setting = true; } return setting; } private get currentMenubarVisibility(): MenuBarVisibility { return this.configurationService.getValue<MenuBarVisibility>('window.menuBarVisibility'); } private get currentTitlebarStyleSetting(): string { return getTitleBarStyle(this.configurationService, this.environmentService); } private get focusState(): MenubarState { return this._focusState; } private set focusState(value: MenubarState) { if (this._focusState >= MenubarState.FOCUSED && value < MenubarState.FOCUSED) { // Losing focus, update the menu if needed if (this.updatePending) { this.menuUpdater.schedule(); this.updatePending = false; } } if (value === this._focusState) { return; } const isVisible = this.isVisible; const isOpen = this.isOpen; const isFocused = this.isFocused; this._focusState = value; switch (value) { case MenubarState.HIDDEN: if (isVisible) { this.hideMenubar(); } if (isOpen) { this.cleanupCustomMenu(); } if (isFocused) { this.focusedMenu = null; if (this.focusToReturn) { this.focusToReturn.focus(); this.focusToReturn = null; } } break; case MenubarState.VISIBLE: if (!isVisible) { this.showMenubar(); } if (isOpen) { this.cleanupCustomMenu(); } if (isFocused) { if (this.focusedMenu) { this.customMenus[this.focusedMenu.index].buttonElement.blur(); } this.focusedMenu = null; if (this.focusToReturn) { this.focusToReturn.focus(); this.focusToReturn = null; } } break; case MenubarState.FOCUSED: if (!isVisible) { this.showMenubar(); } if (isOpen) { this.cleanupCustomMenu(); } if (this.focusedMenu) { this.customMenus[this.focusedMenu.index].buttonElement.focus(); } break; case MenubarState.OPEN: if (!isVisible) { this.showMenubar(); } if (this.focusedMenu) { this.showCustomMenu(this.focusedMenu.index, this.openedViaKeyboard); } break; } this._focusState = value; this._onFocusStateChange.fire(this.focusState >= MenubarState.FOCUSED); } private get mnemonicsInUse(): boolean { return this._mnemonicsInUse; } private set mnemonicsInUse(value: boolean) { this._mnemonicsInUse = value; } private get isVisible(): boolean { return this.focusState >= MenubarState.VISIBLE; } private get isFocused(): boolean { return this.focusState >= MenubarState.FOCUSED; } private get isOpen(): boolean { return this.focusState >= MenubarState.OPEN; } private onDidChangeFullscreen(): void { this.setUnfocusedState(); } private onDidChangeWindowFocus(hasFocus: boolean): void { if (this.container) { if (hasFocus) { DOM.removeClass(this.container, 'inactive'); } else { DOM.addClass(this.container, 'inactive'); this.setUnfocusedState(); this.awaitingAltRelease = false; } } } private onConfigurationUpdated(event: IConfigurationChangeEvent): void { if (this.keys.some(key => event.affectsConfiguration(key))) { this.setupMenubar(); } if (event.affectsConfiguration('window.menuBarVisibility')) { this.setUnfocusedState(); this.detectAndRecommendCustomTitlebar(); } } private setUnfocusedState(): void { if (this.currentMenubarVisibility === 'toggle' || this.currentMenubarVisibility === 'hidden') { this.focusState = MenubarState.HIDDEN; } else if (this.currentMenubarVisibility === 'default' && browser.isFullscreen()) { this.focusState = MenubarState.HIDDEN; } else { this.focusState = MenubarState.VISIBLE; } this.ignoreNextMouseUp = false; this.mnemonicsInUse = false; this.updateMnemonicVisibility(false); } private hideMenubar(): void { if (this.container.style.display !== 'none') { this.container.style.display = 'none'; this._onVisibilityChange.fire(false); } } private showMenubar(): void { if (this.container.style.display !== 'flex') { this.container.style.display = 'flex'; this._onVisibilityChange.fire(true); } } private onModifierKeyToggled(modifierKeyStatus: IModifierKeyStatus): void { const allModifiersReleased = !modifierKeyStatus.altKey && !modifierKeyStatus.ctrlKey && !modifierKeyStatus.shiftKey; if (this.currentMenubarVisibility === 'hidden') { return; } // Alt key pressed while menu is focused. This should return focus away from the menubar if (this.isFocused && modifierKeyStatus.lastKeyPressed === 'alt' && modifierKeyStatus.altKey) { this.setUnfocusedState(); this.mnemonicsInUse = false; this.awaitingAltRelease = true; } // Clean alt key press and release if (allModifiersReleased && modifierKeyStatus.lastKeyPressed === 'alt' && modifierKeyStatus.lastKeyReleased === 'alt') { if (!this.awaitingAltRelease) { if (!this.isFocused) { this.mnemonicsInUse = true; this.focusedMenu = { index: 0 }; this.focusState = MenubarState.FOCUSED; } else if (!this.isOpen) { this.setUnfocusedState(); } } } // Alt key released if (!modifierKeyStatus.altKey && modifierKeyStatus.lastKeyReleased === 'alt') { this.awaitingAltRelease = false; } if (this.currentEnableMenuBarMnemonics && this.customMenus && !this.isOpen) { this.updateMnemonicVisibility((!this.awaitingAltRelease && modifierKeyStatus.altKey) || this.mnemonicsInUse); } } private updateMnemonicVisibility(visible: boolean): void { if (this.customMenus) { this.customMenus.forEach(customMenu => { if (customMenu.titleElement.children.length) { let child = customMenu.titleElement.children.item(0) as HTMLElement; if (child) { child.style.textDecoration = visible ? 'underline' : null; } } }); } } private onRecentlyOpenedChange(): void { this.windowService.getRecentlyOpened().then(recentlyOpened => { this.recentlyOpened = recentlyOpened; this.setupMenubar(); }); } private detectAndRecommendCustomTitlebar(): void { if (!isLinux) { return; } if (!this.storageService.getBoolean('menubar/electronFixRecommended', StorageScope.GLOBAL, false)) { if (this.currentMenubarVisibility === 'hidden' || this.currentTitlebarStyleSetting === 'custom') { // Issue will not arise for user, abort notification return; } const message = nls.localize('menubar.electronFixRecommendation', "If you experience hard to read text in the menu bar, we recommend trying out the custom title bar."); this.notificationService.prompt(Severity.Info, message, [ { label: nls.localize('goToSetting', "Open Settings"), run: () => { return this.preferencesService.openGlobalSettings(undefined, { query: 'window.titleBarStyle' }); } }, { label: nls.localize('moreInfo', "More Info"), run: () => { window.open('https://go.microsoft.com/fwlink/?linkid=2038566'); } }, { label: nls.localize('neverShowAgain', "Don't Show Again"), run: () => { this.storageService.store('menubar/electronFixRecommended', true, StorageScope.GLOBAL); } } ]); } } private registerListeners(): void { // Update when config changes this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e))); // Listen to update service this.updateService.onStateChange(() => this.setupMenubar()); // Listen for changes in recently opened menu this._register(this.windowsService.onRecentlyOpenedChange(() => { this.onRecentlyOpenedChange(); })); // Listen to keybindings change this._register(this.keybindingService.onDidUpdateKeybindings(() => this.setupMenubar())); // These listeners only apply when the custom menubar is being used if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') { // Listen to fullscreen changes this._register(browser.onDidChangeFullscreen(() => this.onDidChangeFullscreen())); // Listen for alt key presses this._register(ModifierKeyEmitter.getInstance(this.windowService).event(this.onModifierKeyToggled, this)); // Listen for window focus changes this._register(this.windowService.onDidChangeFocus(e => this.onDidChangeWindowFocus(e))); } } private doSetupMenubar(): void { if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') { this.setupCustomMenubar(); } else { // Send menus to main process to be rendered by Electron const menubarData = { menus: {}, keybindings: {} }; if (this.getMenubarMenus(menubarData)) { this.menubarService.updateMenubar(this.windowService.getCurrentWindowId(), menubarData); } } } private setupMenubar(): void { this.menuUpdater.schedule(); } private registerMnemonic(menuIndex: number, mnemonic: string): void { this.mnemonics.set(KeyCodeUtils.fromString(mnemonic), menuIndex); } private calculateActionLabel(action: IAction | IMenubarMenuItemAction): string { let label = action.label; switch (action.id) { case 'workbench.action.toggleSidebarPosition': if (this.currentSidebarPosition !== 'right') { label = nls.localize({ key: 'miMoveSidebarRight', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Right"); } else { label = nls.localize({ key: 'miMoveSidebarLeft', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Left"); } break; case 'workbench.action.toggleStatusbarVisibility': if (this.currentStatusBarVisibility) { label = nls.localize({ key: 'miHideStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Hide Status Bar"); } else { label = nls.localize({ key: 'miShowStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Show Status Bar"); } break; case 'workbench.action.toggleActivityBarVisibility': if (this.currentActivityBarVisibility) { label = nls.localize({ key: 'miHideActivityBar', comment: ['&& denotes a mnemonic'] }, "Hide &&Activity Bar"); } else { label = nls.localize({ key: 'miShowActivityBar', comment: ['&& denotes a mnemonic'] }, "Show &&Activity Bar"); } break; default: break; } return label; } private createOpenRecentMenuAction(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI, commandId: string, isFile: boolean): IAction { let label: string; let uri: URI; if (isSingleFolderWorkspaceIdentifier(workspace) && !isFile) { label = this.labelService.getWorkspaceLabel(workspace, { verbose: true }); uri = workspace; } else if (isWorkspaceIdentifier(workspace)) { label = this.labelService.getWorkspaceLabel(workspace, { verbose: true }); uri = URI.file(workspace.configPath); } else { uri = workspace; label = this.labelService.getUriLabel(uri); } return new Action(commandId, label, undefined, undefined, (event) => { const openInNewWindow = event && ((!isMacintosh && (event.ctrlKey || event.shiftKey)) || (isMacintosh && (event.metaKey || event.altKey))); return this.windowService.openWindow([uri], { forceNewWindow: openInNewWindow, forceOpenWorkspaceAsFile: isFile }); }); } private getOpenRecentActions(): IAction[] { if (!this.recentlyOpened) { return []; } const { workspaces, files } = this.recentlyOpened; const result: IAction[] = []; if (workspaces.length > 0) { for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < workspaces.length; i++) { result.push(this.createOpenRecentMenuAction(workspaces[i], 'openRecentWorkspace', false)); } result.push(new Separator()); } if (files.length > 0) { for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) { result.push(this.createOpenRecentMenuAction(files[i], 'openRecentFile', false)); } result.push(new Separator()); } return result; } private getUpdateAction(): IAction | null { const state = this.updateService.state; switch (state.type) { case StateType.Uninitialized: return null; case StateType.Idle: const windowId = this.windowService.getCurrentWindowId(); return new Action('update.check', nls.localize({ key: 'checkForUpdates', comment: ['&& denotes a mnemonic'] }, "Check for &&Updates..."), undefined, true, () => this.updateService.checkForUpdates({ windowId })); case StateType.CheckingForUpdates: return new Action('update.checking', nls.localize('checkingForUpdates', "Checking For Updates..."), undefined, false); case StateType.AvailableForDownload: return new Action('update.downloadNow', nls.localize({ key: 'download now', comment: ['&& denotes a mnemonic'] }, "D&&ownload Now"), null, true, () => this.updateService.downloadUpdate()); case StateType.Downloading: return new Action('update.downloading', nls.localize('DownloadingUpdate', "Downloading Update..."), undefined, false); case StateType.Downloaded: return new Action('update.install', nls.localize({ key: 'installUpdate...', comment: ['&& denotes a mnemonic'] }, "Install &&Update..."), undefined, true, () => this.updateService.applyUpdate()); case StateType.Updating: return new Action('update.updating', nls.localize('installingUpdate', "Installing Update..."), undefined, false); case StateType.Ready: return new Action('update.restart', nls.localize({ key: 'restartToUpdate', comment: ['&& denotes a mnemonic'] }, "Restart to &&Update..."), undefined, true, () => this.updateService.quitAndInstall()); } } private insertActionsBefore(nextAction: IAction, target: IAction[]): void { switch (nextAction.id) { case 'workbench.action.openRecent': target.push(...this.getOpenRecentActions()); break; case 'workbench.action.showAboutDialog': if (!isMacintosh) { const updateAction = this.getUpdateAction(); if (updateAction) { target.push(updateAction); target.push(new Separator()); } } break; default: break; } } private setupCustomMenubar(): void { // Don't update while using the menu if (this.isFocused) { this.updatePending = true; return; } this.container.attributes['role'] = 'menubar'; const firstTimeSetup = this.customMenus === undefined; if (firstTimeSetup) { this.customMenus = []; this.mnemonics = new Map<KeyCode, number>(); } let idx = 0; for (let menuTitle of Object.keys(this.topLevelMenus)) { const menu: IMenu = this.topLevelMenus[menuTitle]; let menuIndex = idx++; const cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]); // Create the top level menu button element if (firstTimeSetup) { const buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true }); const titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true }); buttonElement.appendChild(titleElement); this.container.appendChild(buttonElement); this.customMenus.push({ title: menuTitle, buttonElement: buttonElement, titleElement: titleElement }); } // Update the button label to reflect mnemonics this.customMenus[menuIndex].titleElement.innerHTML = this.currentEnableMenuBarMnemonics ? strings.escape(this.topLevelTitles[menuTitle]).replace(MENU_ESCAPED_MNEMONIC_REGEX, '<mnemonic aria-hidden="true">$1</mnemonic>') : cleanMenuLabel; let mnemonicMatches = MENU_MNEMONIC_REGEX.exec(this.topLevelTitles[menuTitle]); // Register mnemonics if (mnemonicMatches) { let mnemonic = !!mnemonicMatches[1] ? mnemonicMatches[1] : mnemonicMatches[2]; if (firstTimeSetup) { this.registerMnemonic(menuIndex, mnemonic); } if (this.currentEnableMenuBarMnemonics) { this.customMenus[menuIndex].buttonElement.setAttribute('aria-keyshortcuts', 'Alt+' + mnemonic.toLocaleLowerCase()); } else { this.customMenus[menuIndex].buttonElement.removeAttribute('aria-keyshortcuts'); } } // Update the menu actions const updateActions = (menu: IMenu, target: IAction[]) => { target.splice(0); let groups = menu.getActions(); for (let group of groups) { const [, actions] = group; for (let action of actions) { this.insertActionsBefore(action, target); if (action instanceof SubmenuItemAction) { const submenu = this.menuService.createMenu(action.item.submenu, this.contextKeyService); const submenuActions: SubmenuAction[] = []; updateActions(submenu, submenuActions); target.push(new SubmenuAction(action.label, submenuActions)); submenu.dispose(); } else { action.label = this.calculateActionLabel(action); target.push(action); } } target.push(new Separator()); } target.pop(); }; this.customMenus[menuIndex].actions = []; if (firstTimeSetup) { this._register(menu.onDidChange(() => updateActions(menu, this.customMenus[menuIndex].actions))); } updateActions(menu, this.customMenus[menuIndex].actions); if (firstTimeSetup) { this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.KEY_UP, (e) => { let event = new StandardKeyboardEvent(e as KeyboardEvent); let eventHandled = true; if ((event.equals(KeyCode.DownArrow) || event.equals(KeyCode.Enter)) && !this.isOpen) { this.focusedMenu = { index: menuIndex }; this.openedViaKeyboard = true; this.focusState = MenubarState.OPEN; } else { eventHandled = false; } if (eventHandled) { event.preventDefault(); event.stopPropagation(); } })); Gesture.addTarget(this.customMenus[menuIndex].buttonElement); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, EventType.Tap, (e: GestureEvent) => { // Ignore this touch if the menu is touched if (this.isOpen && this.focusedMenu.holder && DOM.isAncestor(e.initialTarget as HTMLElement, this.focusedMenu.holder)) { return; } this.ignoreNextMouseUp = false; this.onMenuTriggered(menuIndex, true); e.preventDefault(); e.stopPropagation(); })); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_DOWN, (e) => { if (!this.isOpen) { // Open the menu with mouse down and ignore the following mouse up event this.ignoreNextMouseUp = true; this.onMenuTriggered(menuIndex, true); } else { this.ignoreNextMouseUp = false; } e.preventDefault(); e.stopPropagation(); })); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_UP, (e) => { if (!this.ignoreNextMouseUp) { if (this.isFocused) { this.onMenuTriggered(menuIndex, true); } } else { this.ignoreNextMouseUp = false; } })); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_ENTER, () => { if (this.isOpen && !this.isCurrentMenu(menuIndex)) { this.customMenus[menuIndex].buttonElement.focus(); this.cleanupCustomMenu(); this.showCustomMenu(menuIndex, false); } else if (this.isFocused && !this.isOpen) { this.focusedMenu = { index: menuIndex }; this.customMenus[menuIndex].buttonElement.focus(); } })); } } if (firstTimeSetup) { this._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => { let event = new StandardKeyboardEvent(e as KeyboardEvent); let eventHandled = true; const key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown; if (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) { this.focusPrevious(); } else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) { this.focusNext(); } else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) { this.setUnfocusedState(); } else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) { const menuIndex = this.mnemonics.get(key); this.onMenuTriggered(menuIndex, false); } else { eventHandled = false; } if (eventHandled) { event.preventDefault(); event.stopPropagation(); } })); this._register(DOM.addDisposableListener(window, DOM.EventType.MOUSE_DOWN, () => { // This mouse event is outside the menubar so it counts as a focus out if (this.isFocused) { this.setUnfocusedState(); } })); this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_IN, (e) => { let event = e as FocusEvent; if (event.relatedTarget) { if (!this.container.contains(event.relatedTarget as HTMLElement)) { this.focusToReturn = event.relatedTarget as HTMLElement; } } })); this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_OUT, (e) => { let event = e as FocusEvent; if (event.relatedTarget) { if (!this.container.contains(event.relatedTarget as HTMLElement)) { this.focusToReturn = null; this.setUnfocusedState(); } } })); this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { if (!this.currentEnableMenuBarMnemonics || !e.altKey || e.ctrlKey || e.defaultPrevented) { return; } const key = KeyCodeUtils.fromString(e.key); if (!this.mnemonics.has(key)) { return; } // Prevent conflicts with keybindings const standardKeyboardEvent = new StandardKeyboardEvent(e); const resolvedResult = this.keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolvedResult) { return; } this.mnemonicsInUse = true; this.updateMnemonicVisibility(true); const menuIndex = this.mnemonics.get(key); this.onMenuTriggered(menuIndex, false); })); } } private onMenuTriggered(menuIndex: number, clicked: boolean) { if (this.isOpen) { if (this.isCurrentMenu(menuIndex)) { this.setUnfocusedState(); } else { this.cleanupCustomMenu(); this.showCustomMenu(menuIndex, this.openedViaKeyboard); } } else { this.focusedMenu = { index: menuIndex }; this.openedViaKeyboard = !clicked; this.focusState = MenubarState.OPEN; } } private focusPrevious(): void { if (!this.focusedMenu) { return; } let newFocusedIndex = (this.focusedMenu.index - 1 + this.customMenus.length) % this.customMenus.length; if (newFocusedIndex === this.focusedMenu.index) { return; } if (this.isOpen) { this.cleanupCustomMenu(); this.showCustomMenu(newFocusedIndex); } else if (this.isFocused) { this.focusedMenu.index = newFocusedIndex; this.customMenus[newFocusedIndex].buttonElement.focus(); } } private focusNext(): void { if (!this.focusedMenu) { return; } let newFocusedIndex = (this.focusedMenu.index + 1) % this.customMenus.length; if (newFocusedIndex === this.focusedMenu.index) { return; } if (this.isOpen) { this.cleanupCustomMenu(); this.showCustomMenu(newFocusedIndex); } else if (this.isFocused) { this.focusedMenu.index = newFocusedIndex; this.customMenus[newFocusedIndex].buttonElement.focus(); } } private getMenubarKeybinding(id: string): IMenubarKeybinding { const binding = this.keybindingService.lookupKeybinding(id); if (!binding) { return undefined; } // first try to resolve a native accelerator const electronAccelerator = binding.getElectronAccelerator(); if (electronAccelerator) { return { label: electronAccelerator }; } // we need this fallback to support keybindings that cannot show in electron menus (e.g. chords) const acceleratorLabel = binding.getLabel(); if (acceleratorLabel) { return { label: acceleratorLabel, isNative: false }; } return null; } private populateMenuItems(menu: IMenu, menuToPopulate: IMenubarMenu, keybindings: { [id: string]: IMenubarKeybinding }) { let groups = menu.getActions(); for (let group of groups) { const [, actions] = group; actions.forEach(menuItem => { if (menuItem instanceof SubmenuItemAction) { const submenu = { items: [] }; const menuToDispose = this.menuService.createMenu(menuItem.item.submenu, this.contextKeyService); this.populateMenuItems(menuToDispose, submenu, keybindings); let menubarSubmenuItem: IMenubarMenuItemSubmenu = { id: menuItem.id, label: menuItem.label, submenu: submenu }; menuToPopulate.items.push(menubarSubmenuItem); menuToDispose.dispose(); } else { let menubarMenuItem: IMenubarMenuItemAction = { id: menuItem.id, label: menuItem.label }; if (menuItem.checked) { menubarMenuItem.checked = true; } if (!menuItem.enabled) { menubarMenuItem.enabled = false; } menubarMenuItem.label = this.calculateActionLabel(menubarMenuItem); keybindings[menuItem.id] = this.getMenubarKeybinding(menuItem.id); menuToPopulate.items.push(menubarMenuItem); } }); menuToPopulate.items.push({ id: 'vscode.menubar.separator' }); } if (menuToPopulate.items.length > 0) { menuToPopulate.items.pop(); } } private getAdditionalKeybindings(): { [id: string]: IMenubarKeybinding } { const keybindings = {}; if (isMacintosh) { keybindings['workbench.action.quit'] = (this.getMenubarKeybinding('workbench.action.quit')); } return keybindings; } private getMenubarMenus(menubarData: IMenubarData): boolean { if (!menubarData) { return false; } menubarData.keybindings = this.getAdditionalKeybindings(); for (let topLevelMenuName of Object.keys(this.topLevelMenus)) { const menu = this.topLevelMenus[topLevelMenuName]; let menubarMenu: IMenubarMenu = { items: [] }; this.populateMenuItems(menu, menubarMenu, menubarData.keybindings); if (menubarMenu.items.length === 0) { // Menus are incomplete return false; } menubarData.menus[topLevelMenuName] = menubarMenu; } return true; } private isCurrentMenu(menuIndex: number): boolean { if (!this.focusedMenu) { return false; } return this.focusedMenu.index === menuIndex; } private cleanupCustomMenu(): void { if (this.focusedMenu) { // Remove focus from the menus first this.customMenus[this.focusedMenu.index].buttonElement.focus(); if (this.focusedMenu.holder) { DOM.removeClass(this.focusedMenu.holder.parentElement, 'open'); this.focusedMenu.holder.remove(); } if (this.focusedMenu.widget) { this.focusedMenu.widget.dispose(); } this.focusedMenu = { index: this.focusedMenu.index }; } } private showCustomMenu(menuIndex: number, selectFirst = true): void { const customMenu = this.customMenus[menuIndex]; const menuHolder = $('div.menubar-menu-items-holder'); DOM.addClass(customMenu.buttonElement, 'open'); menuHolder.style.top = `${this.container.clientHeight}px`; menuHolder.style.left = `${customMenu.buttonElement.getBoundingClientRect().left}px`; customMenu.buttonElement.appendChild(menuHolder); let menuOptions: IMenuOptions = { getKeyBinding: (action) => this.keybindingService.lookupKeybinding(action.id), actionRunner: this.actionRunner, enableMnemonics: this.mnemonicsInUse && this.currentEnableMenuBarMnemonics, ariaLabel: customMenu.buttonElement.attributes['aria-label'].value }; let menuWidget = this._register(new Menu(menuHolder, customMenu.actions, menuOptions)); this._register(attachMenuStyler(menuWidget, this.themeService)); this._register(menuWidget.onDidCancel(() => { this.focusState = MenubarState.FOCUSED; })); this._register(menuWidget.onDidBlur(() => { setTimeout(() => { this.cleanupCustomMenu(); }, 100); })); menuWidget.focus(selectFirst); this.focusedMenu = { index: menuIndex, holder: menuHolder, widget: menuWidget }; } public get onVisibilityChange(): Event<boolean> { return this._onVisibilityChange.event; } public get onFocusStateChange(): Event<boolean> { return this._onFocusStateChange.event; } public layout(dimension: DOM.Dimension) { if (this.container) { this.container.style.height = `${dimension.height}px`; } if (!this.isVisible) { this.hideMenubar(); } else { this.showMenubar(); } } public getMenubarItemsDimensions(): DOM.Dimension { if (this.customMenus) { const left = this.customMenus[0].buttonElement.getBoundingClientRect().left; const right = this.customMenus[this.customMenus.length - 1].buttonElement.getBoundingClientRect().right; return new DOM.Dimension(right - left, this.container.clientHeight); } return new DOM.Dimension(0, 0); } public create(parent: HTMLElement): HTMLElement { this.container = parent; // Build the menubar if (this.container) { this.doSetupMenubar(); if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') { this.setUnfocusedState(); } } return this.container; } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { const menubarActiveWindowFgColor = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (menubarActiveWindowFgColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button { color: ${menubarActiveWindowFgColor}; } `); } const menubarInactiveWindowFgColor = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (menubarInactiveWindowFgColor) { collector.addRule(` .monaco-workbench .menubar.inactive > .menubar-menu-button { color: ${menubarInactiveWindowFgColor}; } `); } const menubarSelectedFgColor = theme.getColor(MENUBAR_SELECTION_FOREGROUND); if (menubarSelectedFgColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus, .monaco-workbench .menubar:not(:focus-within) > .menubar-menu-button:hover { color: ${menubarSelectedFgColor}; } `); } const menubarSelectedBgColor = theme.getColor(MENUBAR_SELECTION_BACKGROUND); if (menubarSelectedBgColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus, .monaco-workbench .menubar:not(:focus-within) > .menubar-menu-button:hover { background-color: ${menubarSelectedBgColor}; } `); } const menubarSelectedBorderColor = theme.getColor(MENUBAR_SELECTION_BORDER); if (menubarSelectedBorderColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button:hover { outline: dashed 1px; } .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus { outline: solid 1px; } .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus, .monaco-workbench .menubar > .menubar-menu-button:hover { outline-offset: -1px; outline-color: ${menubarSelectedBorderColor}; } `); } }); type ModifierKey = 'alt' | 'ctrl' | 'shift'; interface IModifierKeyStatus { altKey: boolean; shiftKey: boolean; ctrlKey: boolean; lastKeyPressed?: ModifierKey; lastKeyReleased?: ModifierKey; } class ModifierKeyEmitter extends Emitter<IModifierKeyStatus> { private _subscriptions: IDisposable[] = []; private _keyStatus: IModifierKeyStatus; private static instance: ModifierKeyEmitter; private constructor(windowService: IWindowService) { super(); this._keyStatus = { altKey: false, shiftKey: false, ctrlKey: false }; this._subscriptions.push(domEvent(document.body, 'keydown')(e => { const event = new StandardKeyboardEvent(e); if (e.altKey && !this._keyStatus.altKey) { this._keyStatus.lastKeyPressed = 'alt'; } else if (e.ctrlKey && !this._keyStatus.ctrlKey) { this._keyStatus.lastKeyPressed = 'ctrl'; } else if (e.shiftKey && !this._keyStatus.shiftKey) { this._keyStatus.lastKeyPressed = 'shift'; } else if (event.keyCode !== KeyCode.Alt) { this._keyStatus.lastKeyPressed = undefined; } else { return; } this._keyStatus.altKey = e.altKey; this._keyStatus.ctrlKey = e.ctrlKey; this._keyStatus.shiftKey = e.shiftKey; if (this._keyStatus.lastKeyPressed) { this.fire(this._keyStatus); } })); this._subscriptions.push(domEvent(document.body, 'keyup')(e => { if (!e.altKey && this._keyStatus.altKey) { this._keyStatus.lastKeyReleased = 'alt'; } else if (!e.ctrlKey && this._keyStatus.ctrlKey) { this._keyStatus.lastKeyReleased = 'ctrl'; } else if (!e.shiftKey && this._keyStatus.shiftKey) { this._keyStatus.lastKeyReleased = 'shift'; } else { this._keyStatus.lastKeyReleased = undefined; } if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) { this._keyStatus.lastKeyPressed = undefined; } this._keyStatus.altKey = e.altKey; this._keyStatus.ctrlKey = e.ctrlKey; this._keyStatus.shiftKey = e.shiftKey; if (this._keyStatus.lastKeyReleased) { this.fire(this._keyStatus); } })); this._subscriptions.push(domEvent(document.body, 'mousedown')(e => { this._keyStatus.lastKeyPressed = undefined; })); this._subscriptions.push(windowService.onDidChangeFocus(focused => { if (!focused) { this._keyStatus.lastKeyPressed = undefined; this._keyStatus.lastKeyReleased = undefined; this._keyStatus.altKey = false; this._keyStatus.shiftKey = false; this._keyStatus.shiftKey = false; this.fire(this._keyStatus); } })); } static getInstance(windowService: IWindowService) { if (!ModifierKeyEmitter.instance) { ModifierKeyEmitter.instance = new ModifierKeyEmitter(windowService); } return ModifierKeyEmitter.instance; } dispose() { super.dispose(); this._subscriptions = dispose(this._subscriptions); } }
src/vs/workbench/browser/parts/titlebar/menubarControl.ts
1
https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535
[ 0.02260882407426834, 0.0006981497281230986, 0.00016324600437656045, 0.0001751429954310879, 0.002258528023958206 ]
{ "id": 0, "code_window": [ "\tcursor: default;\n", "\t-webkit-app-region: no-drag;\n", "\tzoom: 1;\n", "\twhite-space: nowrap;\n", "}\n", "\n", ".monaco-workbench .menubar .menubar-menu-items-holder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css", "type": "add", "edit_start_line_idx": 185 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#646465" d="M6 4v8l4-4-4-4zm1 2.414L8.586 8 7 9.586V6.414z"/></svg>
src/vs/base/browser/ui/breadcrumbs/collapsed.svg
0
https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535
[ 0.0001740193838486448, 0.0001740193838486448, 0.0001740193838486448, 0.0001740193838486448, 0 ]
{ "id": 0, "code_window": [ "\tcursor: default;\n", "\t-webkit-app-region: no-drag;\n", "\tzoom: 1;\n", "\twhite-space: nowrap;\n", "}\n", "\n", ".monaco-workbench .menubar .menubar-menu-items-holder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css", "type": "add", "edit_start_line_idx": 185 }
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><style>.icon-canvas-transparent{opacity:0;fill:#252526}.icon-vs-out{fill:#252526}.icon-vs-bg{fill:#c5c5c5}.icon-vs-fg{fill:#2b282e}.icon-vs-action-blue{fill:#75beff}</style><path class="icon-canvas-transparent" d="M16 16H0V0h16v16z" id="canvas"/><path class="icon-vs-out" d="M2.879 14L1 12.121V3.879L2.879 2h10.242L15 3.879v8.242L13.121 14H2.879z" id="outline"/><path class="icon-vs-fg" d="M12.293 4H3.707L3 4.707v6.586l.707.707h8.586l.707-.707V4.707L12.293 4zM11 10H5V9h6v1zm0-3H5V6h6v1z" id="iconFg"/><g id="iconBg"><path class="icon-vs-bg" d="M12.707 13H3.293L2 11.707V4.293L3.293 3h9.414L14 4.293v7.414L12.707 13zm-9-1h8.586l.707-.707V4.707L12.293 4H3.707L3 4.707v6.586l.707.707z"/><path class="icon-vs-action-blue" d="M11 7H5V6h6v1zm0 2H5v1h6V9z"/></g></svg>
src/vs/editor/contrib/suggest/media/Constant_16x_inverse.svg
0
https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535
[ 0.00043115305015817285, 0.00043115305015817285, 0.00043115305015817285, 0.00043115305015817285, 0 ]
{ "id": 0, "code_window": [ "\tcursor: default;\n", "\t-webkit-app-region: no-drag;\n", "\tzoom: 1;\n", "\twhite-space: nowrap;\n", "}\n", "\n", ".monaco-workbench .menubar .menubar-menu-items-holder {\n", "\tposition: absolute;\n" ], "labels": [ "keep", "keep", "keep", "add", "keep", "keep", "keep", "keep" ], "after_edit": [ "\toutline: 0;\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/media/titlebarpart.css", "type": "add", "edit_start_line_idx": 185 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions'; import { TERMINAL_COMMAND_ID } from 'vs/workbench/parts/terminal/common/terminalCommands'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; export function setupTerminalMenu() { // View menu MenuRegistry.appendMenuItem(MenuId.MenubarViewMenu, { group: '4_panels', command: { id: TERMINAL_COMMAND_ID.TOGGLE, title: nls.localize({ key: 'miToggleIntegratedTerminal', comment: ['&& denotes a mnemonic'] }, "&&Terminal") }, order: 3 }); // Manage const createGroup = '1_create'; MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: createGroup, command: { id: TERMINAL_COMMAND_ID.NEW, title: nls.localize({ key: 'miNewTerminal', comment: ['&& denotes a mnemonic'] }, "&&New Terminal") }, order: 1 }); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: createGroup, command: { id: TERMINAL_COMMAND_ID.SPLIT, title: nls.localize({ key: 'miSplitTerminal', comment: ['&& denotes a mnemonic'] }, "&&Split Terminal"), precondition: ContextKeyExpr.has('terminalIsOpen') }, order: 2 }); // Run const runGroup = '2_run'; MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: runGroup, command: { id: TERMINAL_COMMAND_ID.RUN_ACTIVE_FILE, title: nls.localize({ key: 'miRunActiveFile', comment: ['&& denotes a mnemonic'] }, "Run &&Active File") }, order: 3 }); MenuRegistry.appendMenuItem(MenuId.MenubarTerminalMenu, { group: runGroup, command: { id: TERMINAL_COMMAND_ID.RUN_SELECTED_TEXT, title: nls.localize({ key: 'miRunSelectedText', comment: ['&& denotes a mnemonic'] }, "Run &&Selected Text") }, order: 4 }); }
src/vs/workbench/parts/terminal/common/terminalMenu.ts
0
https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535
[ 0.00035924173425883055, 0.00022592746245209128, 0.00016672079800628126, 0.00017733241838868707, 0.00007326064951485023 ]
{ "id": 1, "code_window": [ "\t\t\tconst cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]);\n", "\n", "\t\t\t// Create the top level menu button element\n", "\t\t\tif (firstTimeSetup) {\n", "\n", "\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n", "\t\t\t\tconst titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true });\n", "\n", "\t\t\t\tbuttonElement.appendChild(titleElement);\n", "\t\t\t\tthis.container.appendChild(buttonElement);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': -1, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts", "type": "replace", "edit_start_line_idx": 700 }
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as browser from 'vs/base/browser/browser'; import * as strings from 'vs/base/common/strings'; import { IMenubarMenu, IMenubarMenuItemAction, IMenubarMenuItemSubmenu, IMenubarKeybinding, IMenubarService, IMenubarData } from 'vs/platform/menubar/common/menubar'; import { IMenuService, MenuId, IMenu, SubmenuItemAction } from 'vs/platform/actions/common/actions'; import { registerThemingParticipant, ITheme, ICssStyleCollector, IThemeService } from 'vs/platform/theme/common/themeService'; import { IWindowService, MenuBarVisibility, IWindowsService, getTitleBarStyle } from 'vs/platform/windows/common/windows'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { ActionRunner, IActionRunner, IAction, Action } from 'vs/base/common/actions'; import { Separator } from 'vs/base/browser/ui/actionbar/actionbar'; import * as DOM from 'vs/base/browser/dom'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { isMacintosh, isLinux } from 'vs/base/common/platform'; import { Menu, IMenuOptions, SubmenuAction, MENU_MNEMONIC_REGEX, cleanMnemonic, MENU_ESCAPED_MNEMONIC_REGEX } from 'vs/base/browser/ui/menu/menu'; import { KeyCode, KeyCodeUtils } from 'vs/base/common/keyCodes'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { IConfigurationService, IConfigurationChangeEvent } from 'vs/platform/configuration/common/configuration'; import { Event, Emitter } from 'vs/base/common/event'; import { IDisposable, Disposable, dispose } from 'vs/base/common/lifecycle'; import { domEvent } from 'vs/base/browser/event'; import { IRecentlyOpened } from 'vs/platform/history/common/history'; import { IWorkspaceIdentifier, ISingleFolderWorkspaceIdentifier, isSingleFolderWorkspaceIdentifier, isWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces'; import { RunOnceScheduler } from 'vs/base/common/async'; import { MENUBAR_SELECTION_FOREGROUND, MENUBAR_SELECTION_BACKGROUND, MENUBAR_SELECTION_BORDER, TITLE_BAR_ACTIVE_FOREGROUND, TITLE_BAR_INACTIVE_FOREGROUND } from 'vs/workbench/common/theme'; import { URI } from 'vs/base/common/uri'; import { ILabelService } from 'vs/platform/label/common/label'; import { IUpdateService, StateType } from 'vs/platform/update/common/update'; import { Gesture, EventType, GestureEvent } from 'vs/base/browser/touch'; import { attachMenuStyler } from 'vs/platform/theme/common/styler'; import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage'; import { INotificationService, Severity } from 'vs/platform/notification/common/notification'; import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; const $ = DOM.$; interface CustomMenu { title: string; buttonElement: HTMLElement; titleElement: HTMLElement; actions?: IAction[]; } enum MenubarState { HIDDEN, VISIBLE, FOCUSED, OPEN } export class MenubarControl extends Disposable { private keys = [ 'files.autoSave', 'window.menuBarVisibility', 'editor.multiCursorModifier', 'workbench.sideBar.location', 'workbench.statusBar.visible', 'workbench.activityBar.visible', 'window.enableMenuBarMnemonics', 'window.nativeTabs' ]; private topLevelMenus: { 'File': IMenu; 'Edit': IMenu; 'Selection': IMenu; 'View': IMenu; 'Go': IMenu; 'Debug': IMenu; 'Terminal': IMenu; 'Window'?: IMenu; 'Help': IMenu; [index: string]: IMenu; }; private topLevelTitles = { 'File': nls.localize({ key: 'mFile', comment: ['&& denotes a mnemonic'] }, "&&File"), 'Edit': nls.localize({ key: 'mEdit', comment: ['&& denotes a mnemonic'] }, "&&Edit"), 'Selection': nls.localize({ key: 'mSelection', comment: ['&& denotes a mnemonic'] }, "&&Selection"), 'View': nls.localize({ key: 'mView', comment: ['&& denotes a mnemonic'] }, "&&View"), 'Go': nls.localize({ key: 'mGoto', comment: ['&& denotes a mnemonic'] }, "&&Go"), 'Debug': nls.localize({ key: 'mDebug', comment: ['&& denotes a mnemonic'] }, "&&Debug"), 'Terminal': nls.localize({ key: 'mTerminal', comment: ['&& denotes a mnemonic'] }, "&&Terminal"), 'Help': nls.localize({ key: 'mHelp', comment: ['&& denotes a mnemonic'] }, "&&Help") }; private focusedMenu: { index: number; holder?: HTMLElement; widget?: Menu; }; private customMenus: CustomMenu[]; private menuUpdater: RunOnceScheduler; private actionRunner: IActionRunner; private focusToReturn: HTMLElement; private container: HTMLElement; private recentlyOpened: IRecentlyOpened; private updatePending: boolean; private _focusState: MenubarState; // Input-related private _mnemonicsInUse: boolean; private openedViaKeyboard: boolean; private awaitingAltRelease: boolean; private ignoreNextMouseUp: boolean; private mnemonics: Map<KeyCode, number>; private _onVisibilityChange: Emitter<boolean>; private _onFocusStateChange: Emitter<boolean>; private static MAX_MENU_RECENT_ENTRIES = 10; constructor( @IThemeService private themeService: IThemeService, @IMenubarService private menubarService: IMenubarService, @IMenuService private menuService: IMenuService, @IWindowService private windowService: IWindowService, @IWindowsService private windowsService: IWindowsService, @IContextKeyService private contextKeyService: IContextKeyService, @IKeybindingService private keybindingService: IKeybindingService, @IConfigurationService private configurationService: IConfigurationService, @ILabelService private labelService: ILabelService, @IUpdateService private updateService: IUpdateService, @IStorageService private storageService: IStorageService, @INotificationService private notificationService: INotificationService, @IPreferencesService private preferencesService: IPreferencesService, @IEnvironmentService private environmentService: IEnvironmentService ) { super(); this.topLevelMenus = { 'File': this._register(this.menuService.createMenu(MenuId.MenubarFileMenu, this.contextKeyService)), 'Edit': this._register(this.menuService.createMenu(MenuId.MenubarEditMenu, this.contextKeyService)), 'Selection': this._register(this.menuService.createMenu(MenuId.MenubarSelectionMenu, this.contextKeyService)), 'View': this._register(this.menuService.createMenu(MenuId.MenubarViewMenu, this.contextKeyService)), 'Go': this._register(this.menuService.createMenu(MenuId.MenubarGoMenu, this.contextKeyService)), 'Debug': this._register(this.menuService.createMenu(MenuId.MenubarDebugMenu, this.contextKeyService)), 'Terminal': this._register(this.menuService.createMenu(MenuId.MenubarTerminalMenu, this.contextKeyService)), 'Help': this._register(this.menuService.createMenu(MenuId.MenubarHelpMenu, this.contextKeyService)) }; if (isMacintosh) { this.topLevelMenus['Preferences'] = this._register(this.menuService.createMenu(MenuId.MenubarPreferencesMenu, this.contextKeyService)); } this.menuUpdater = this._register(new RunOnceScheduler(() => this.doSetupMenubar(), 200)); this.actionRunner = this._register(new ActionRunner()); this._register(this.actionRunner.onDidBeforeRun(() => { this.setUnfocusedState(); })); this._onVisibilityChange = this._register(new Emitter<boolean>()); this._onFocusStateChange = this._register(new Emitter<boolean>()); if (isMacintosh || this.currentTitlebarStyleSetting !== 'custom') { for (let topLevelMenuName of Object.keys(this.topLevelMenus)) { this._register(this.topLevelMenus[topLevelMenuName].onDidChange(() => this.setupMenubar())); } this.doSetupMenubar(); } this._focusState = MenubarState.HIDDEN; this.windowService.getRecentlyOpened().then((recentlyOpened) => { this.recentlyOpened = recentlyOpened; }); this.detectAndRecommendCustomTitlebar(); this.registerListeners(); } private get currentEnableMenuBarMnemonics(): boolean { let enableMenuBarMnemonics = this.configurationService.getValue<boolean>('window.enableMenuBarMnemonics'); if (typeof enableMenuBarMnemonics !== 'boolean') { enableMenuBarMnemonics = true; } return enableMenuBarMnemonics; } private get currentSidebarPosition(): string { return this.configurationService.getValue<string>('workbench.sideBar.location'); } private get currentStatusBarVisibility(): boolean { let setting = this.configurationService.getValue<boolean>('workbench.statusBar.visible'); if (typeof setting !== 'boolean') { setting = true; } return setting; } private get currentActivityBarVisibility(): boolean { let setting = this.configurationService.getValue<boolean>('workbench.activityBar.visible'); if (typeof setting !== 'boolean') { setting = true; } return setting; } private get currentMenubarVisibility(): MenuBarVisibility { return this.configurationService.getValue<MenuBarVisibility>('window.menuBarVisibility'); } private get currentTitlebarStyleSetting(): string { return getTitleBarStyle(this.configurationService, this.environmentService); } private get focusState(): MenubarState { return this._focusState; } private set focusState(value: MenubarState) { if (this._focusState >= MenubarState.FOCUSED && value < MenubarState.FOCUSED) { // Losing focus, update the menu if needed if (this.updatePending) { this.menuUpdater.schedule(); this.updatePending = false; } } if (value === this._focusState) { return; } const isVisible = this.isVisible; const isOpen = this.isOpen; const isFocused = this.isFocused; this._focusState = value; switch (value) { case MenubarState.HIDDEN: if (isVisible) { this.hideMenubar(); } if (isOpen) { this.cleanupCustomMenu(); } if (isFocused) { this.focusedMenu = null; if (this.focusToReturn) { this.focusToReturn.focus(); this.focusToReturn = null; } } break; case MenubarState.VISIBLE: if (!isVisible) { this.showMenubar(); } if (isOpen) { this.cleanupCustomMenu(); } if (isFocused) { if (this.focusedMenu) { this.customMenus[this.focusedMenu.index].buttonElement.blur(); } this.focusedMenu = null; if (this.focusToReturn) { this.focusToReturn.focus(); this.focusToReturn = null; } } break; case MenubarState.FOCUSED: if (!isVisible) { this.showMenubar(); } if (isOpen) { this.cleanupCustomMenu(); } if (this.focusedMenu) { this.customMenus[this.focusedMenu.index].buttonElement.focus(); } break; case MenubarState.OPEN: if (!isVisible) { this.showMenubar(); } if (this.focusedMenu) { this.showCustomMenu(this.focusedMenu.index, this.openedViaKeyboard); } break; } this._focusState = value; this._onFocusStateChange.fire(this.focusState >= MenubarState.FOCUSED); } private get mnemonicsInUse(): boolean { return this._mnemonicsInUse; } private set mnemonicsInUse(value: boolean) { this._mnemonicsInUse = value; } private get isVisible(): boolean { return this.focusState >= MenubarState.VISIBLE; } private get isFocused(): boolean { return this.focusState >= MenubarState.FOCUSED; } private get isOpen(): boolean { return this.focusState >= MenubarState.OPEN; } private onDidChangeFullscreen(): void { this.setUnfocusedState(); } private onDidChangeWindowFocus(hasFocus: boolean): void { if (this.container) { if (hasFocus) { DOM.removeClass(this.container, 'inactive'); } else { DOM.addClass(this.container, 'inactive'); this.setUnfocusedState(); this.awaitingAltRelease = false; } } } private onConfigurationUpdated(event: IConfigurationChangeEvent): void { if (this.keys.some(key => event.affectsConfiguration(key))) { this.setupMenubar(); } if (event.affectsConfiguration('window.menuBarVisibility')) { this.setUnfocusedState(); this.detectAndRecommendCustomTitlebar(); } } private setUnfocusedState(): void { if (this.currentMenubarVisibility === 'toggle' || this.currentMenubarVisibility === 'hidden') { this.focusState = MenubarState.HIDDEN; } else if (this.currentMenubarVisibility === 'default' && browser.isFullscreen()) { this.focusState = MenubarState.HIDDEN; } else { this.focusState = MenubarState.VISIBLE; } this.ignoreNextMouseUp = false; this.mnemonicsInUse = false; this.updateMnemonicVisibility(false); } private hideMenubar(): void { if (this.container.style.display !== 'none') { this.container.style.display = 'none'; this._onVisibilityChange.fire(false); } } private showMenubar(): void { if (this.container.style.display !== 'flex') { this.container.style.display = 'flex'; this._onVisibilityChange.fire(true); } } private onModifierKeyToggled(modifierKeyStatus: IModifierKeyStatus): void { const allModifiersReleased = !modifierKeyStatus.altKey && !modifierKeyStatus.ctrlKey && !modifierKeyStatus.shiftKey; if (this.currentMenubarVisibility === 'hidden') { return; } // Alt key pressed while menu is focused. This should return focus away from the menubar if (this.isFocused && modifierKeyStatus.lastKeyPressed === 'alt' && modifierKeyStatus.altKey) { this.setUnfocusedState(); this.mnemonicsInUse = false; this.awaitingAltRelease = true; } // Clean alt key press and release if (allModifiersReleased && modifierKeyStatus.lastKeyPressed === 'alt' && modifierKeyStatus.lastKeyReleased === 'alt') { if (!this.awaitingAltRelease) { if (!this.isFocused) { this.mnemonicsInUse = true; this.focusedMenu = { index: 0 }; this.focusState = MenubarState.FOCUSED; } else if (!this.isOpen) { this.setUnfocusedState(); } } } // Alt key released if (!modifierKeyStatus.altKey && modifierKeyStatus.lastKeyReleased === 'alt') { this.awaitingAltRelease = false; } if (this.currentEnableMenuBarMnemonics && this.customMenus && !this.isOpen) { this.updateMnemonicVisibility((!this.awaitingAltRelease && modifierKeyStatus.altKey) || this.mnemonicsInUse); } } private updateMnemonicVisibility(visible: boolean): void { if (this.customMenus) { this.customMenus.forEach(customMenu => { if (customMenu.titleElement.children.length) { let child = customMenu.titleElement.children.item(0) as HTMLElement; if (child) { child.style.textDecoration = visible ? 'underline' : null; } } }); } } private onRecentlyOpenedChange(): void { this.windowService.getRecentlyOpened().then(recentlyOpened => { this.recentlyOpened = recentlyOpened; this.setupMenubar(); }); } private detectAndRecommendCustomTitlebar(): void { if (!isLinux) { return; } if (!this.storageService.getBoolean('menubar/electronFixRecommended', StorageScope.GLOBAL, false)) { if (this.currentMenubarVisibility === 'hidden' || this.currentTitlebarStyleSetting === 'custom') { // Issue will not arise for user, abort notification return; } const message = nls.localize('menubar.electronFixRecommendation', "If you experience hard to read text in the menu bar, we recommend trying out the custom title bar."); this.notificationService.prompt(Severity.Info, message, [ { label: nls.localize('goToSetting', "Open Settings"), run: () => { return this.preferencesService.openGlobalSettings(undefined, { query: 'window.titleBarStyle' }); } }, { label: nls.localize('moreInfo', "More Info"), run: () => { window.open('https://go.microsoft.com/fwlink/?linkid=2038566'); } }, { label: nls.localize('neverShowAgain', "Don't Show Again"), run: () => { this.storageService.store('menubar/electronFixRecommended', true, StorageScope.GLOBAL); } } ]); } } private registerListeners(): void { // Update when config changes this._register(this.configurationService.onDidChangeConfiguration(e => this.onConfigurationUpdated(e))); // Listen to update service this.updateService.onStateChange(() => this.setupMenubar()); // Listen for changes in recently opened menu this._register(this.windowsService.onRecentlyOpenedChange(() => { this.onRecentlyOpenedChange(); })); // Listen to keybindings change this._register(this.keybindingService.onDidUpdateKeybindings(() => this.setupMenubar())); // These listeners only apply when the custom menubar is being used if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') { // Listen to fullscreen changes this._register(browser.onDidChangeFullscreen(() => this.onDidChangeFullscreen())); // Listen for alt key presses this._register(ModifierKeyEmitter.getInstance(this.windowService).event(this.onModifierKeyToggled, this)); // Listen for window focus changes this._register(this.windowService.onDidChangeFocus(e => this.onDidChangeWindowFocus(e))); } } private doSetupMenubar(): void { if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') { this.setupCustomMenubar(); } else { // Send menus to main process to be rendered by Electron const menubarData = { menus: {}, keybindings: {} }; if (this.getMenubarMenus(menubarData)) { this.menubarService.updateMenubar(this.windowService.getCurrentWindowId(), menubarData); } } } private setupMenubar(): void { this.menuUpdater.schedule(); } private registerMnemonic(menuIndex: number, mnemonic: string): void { this.mnemonics.set(KeyCodeUtils.fromString(mnemonic), menuIndex); } private calculateActionLabel(action: IAction | IMenubarMenuItemAction): string { let label = action.label; switch (action.id) { case 'workbench.action.toggleSidebarPosition': if (this.currentSidebarPosition !== 'right') { label = nls.localize({ key: 'miMoveSidebarRight', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Right"); } else { label = nls.localize({ key: 'miMoveSidebarLeft', comment: ['&& denotes a mnemonic'] }, "&&Move Side Bar Left"); } break; case 'workbench.action.toggleStatusbarVisibility': if (this.currentStatusBarVisibility) { label = nls.localize({ key: 'miHideStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Hide Status Bar"); } else { label = nls.localize({ key: 'miShowStatusbar', comment: ['&& denotes a mnemonic'] }, "&&Show Status Bar"); } break; case 'workbench.action.toggleActivityBarVisibility': if (this.currentActivityBarVisibility) { label = nls.localize({ key: 'miHideActivityBar', comment: ['&& denotes a mnemonic'] }, "Hide &&Activity Bar"); } else { label = nls.localize({ key: 'miShowActivityBar', comment: ['&& denotes a mnemonic'] }, "Show &&Activity Bar"); } break; default: break; } return label; } private createOpenRecentMenuAction(workspace: IWorkspaceIdentifier | ISingleFolderWorkspaceIdentifier | URI, commandId: string, isFile: boolean): IAction { let label: string; let uri: URI; if (isSingleFolderWorkspaceIdentifier(workspace) && !isFile) { label = this.labelService.getWorkspaceLabel(workspace, { verbose: true }); uri = workspace; } else if (isWorkspaceIdentifier(workspace)) { label = this.labelService.getWorkspaceLabel(workspace, { verbose: true }); uri = URI.file(workspace.configPath); } else { uri = workspace; label = this.labelService.getUriLabel(uri); } return new Action(commandId, label, undefined, undefined, (event) => { const openInNewWindow = event && ((!isMacintosh && (event.ctrlKey || event.shiftKey)) || (isMacintosh && (event.metaKey || event.altKey))); return this.windowService.openWindow([uri], { forceNewWindow: openInNewWindow, forceOpenWorkspaceAsFile: isFile }); }); } private getOpenRecentActions(): IAction[] { if (!this.recentlyOpened) { return []; } const { workspaces, files } = this.recentlyOpened; const result: IAction[] = []; if (workspaces.length > 0) { for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < workspaces.length; i++) { result.push(this.createOpenRecentMenuAction(workspaces[i], 'openRecentWorkspace', false)); } result.push(new Separator()); } if (files.length > 0) { for (let i = 0; i < MenubarControl.MAX_MENU_RECENT_ENTRIES && i < files.length; i++) { result.push(this.createOpenRecentMenuAction(files[i], 'openRecentFile', false)); } result.push(new Separator()); } return result; } private getUpdateAction(): IAction | null { const state = this.updateService.state; switch (state.type) { case StateType.Uninitialized: return null; case StateType.Idle: const windowId = this.windowService.getCurrentWindowId(); return new Action('update.check', nls.localize({ key: 'checkForUpdates', comment: ['&& denotes a mnemonic'] }, "Check for &&Updates..."), undefined, true, () => this.updateService.checkForUpdates({ windowId })); case StateType.CheckingForUpdates: return new Action('update.checking', nls.localize('checkingForUpdates', "Checking For Updates..."), undefined, false); case StateType.AvailableForDownload: return new Action('update.downloadNow', nls.localize({ key: 'download now', comment: ['&& denotes a mnemonic'] }, "D&&ownload Now"), null, true, () => this.updateService.downloadUpdate()); case StateType.Downloading: return new Action('update.downloading', nls.localize('DownloadingUpdate', "Downloading Update..."), undefined, false); case StateType.Downloaded: return new Action('update.install', nls.localize({ key: 'installUpdate...', comment: ['&& denotes a mnemonic'] }, "Install &&Update..."), undefined, true, () => this.updateService.applyUpdate()); case StateType.Updating: return new Action('update.updating', nls.localize('installingUpdate', "Installing Update..."), undefined, false); case StateType.Ready: return new Action('update.restart', nls.localize({ key: 'restartToUpdate', comment: ['&& denotes a mnemonic'] }, "Restart to &&Update..."), undefined, true, () => this.updateService.quitAndInstall()); } } private insertActionsBefore(nextAction: IAction, target: IAction[]): void { switch (nextAction.id) { case 'workbench.action.openRecent': target.push(...this.getOpenRecentActions()); break; case 'workbench.action.showAboutDialog': if (!isMacintosh) { const updateAction = this.getUpdateAction(); if (updateAction) { target.push(updateAction); target.push(new Separator()); } } break; default: break; } } private setupCustomMenubar(): void { // Don't update while using the menu if (this.isFocused) { this.updatePending = true; return; } this.container.attributes['role'] = 'menubar'; const firstTimeSetup = this.customMenus === undefined; if (firstTimeSetup) { this.customMenus = []; this.mnemonics = new Map<KeyCode, number>(); } let idx = 0; for (let menuTitle of Object.keys(this.topLevelMenus)) { const menu: IMenu = this.topLevelMenus[menuTitle]; let menuIndex = idx++; const cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]); // Create the top level menu button element if (firstTimeSetup) { const buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true }); const titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true }); buttonElement.appendChild(titleElement); this.container.appendChild(buttonElement); this.customMenus.push({ title: menuTitle, buttonElement: buttonElement, titleElement: titleElement }); } // Update the button label to reflect mnemonics this.customMenus[menuIndex].titleElement.innerHTML = this.currentEnableMenuBarMnemonics ? strings.escape(this.topLevelTitles[menuTitle]).replace(MENU_ESCAPED_MNEMONIC_REGEX, '<mnemonic aria-hidden="true">$1</mnemonic>') : cleanMenuLabel; let mnemonicMatches = MENU_MNEMONIC_REGEX.exec(this.topLevelTitles[menuTitle]); // Register mnemonics if (mnemonicMatches) { let mnemonic = !!mnemonicMatches[1] ? mnemonicMatches[1] : mnemonicMatches[2]; if (firstTimeSetup) { this.registerMnemonic(menuIndex, mnemonic); } if (this.currentEnableMenuBarMnemonics) { this.customMenus[menuIndex].buttonElement.setAttribute('aria-keyshortcuts', 'Alt+' + mnemonic.toLocaleLowerCase()); } else { this.customMenus[menuIndex].buttonElement.removeAttribute('aria-keyshortcuts'); } } // Update the menu actions const updateActions = (menu: IMenu, target: IAction[]) => { target.splice(0); let groups = menu.getActions(); for (let group of groups) { const [, actions] = group; for (let action of actions) { this.insertActionsBefore(action, target); if (action instanceof SubmenuItemAction) { const submenu = this.menuService.createMenu(action.item.submenu, this.contextKeyService); const submenuActions: SubmenuAction[] = []; updateActions(submenu, submenuActions); target.push(new SubmenuAction(action.label, submenuActions)); submenu.dispose(); } else { action.label = this.calculateActionLabel(action); target.push(action); } } target.push(new Separator()); } target.pop(); }; this.customMenus[menuIndex].actions = []; if (firstTimeSetup) { this._register(menu.onDidChange(() => updateActions(menu, this.customMenus[menuIndex].actions))); } updateActions(menu, this.customMenus[menuIndex].actions); if (firstTimeSetup) { this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.KEY_UP, (e) => { let event = new StandardKeyboardEvent(e as KeyboardEvent); let eventHandled = true; if ((event.equals(KeyCode.DownArrow) || event.equals(KeyCode.Enter)) && !this.isOpen) { this.focusedMenu = { index: menuIndex }; this.openedViaKeyboard = true; this.focusState = MenubarState.OPEN; } else { eventHandled = false; } if (eventHandled) { event.preventDefault(); event.stopPropagation(); } })); Gesture.addTarget(this.customMenus[menuIndex].buttonElement); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, EventType.Tap, (e: GestureEvent) => { // Ignore this touch if the menu is touched if (this.isOpen && this.focusedMenu.holder && DOM.isAncestor(e.initialTarget as HTMLElement, this.focusedMenu.holder)) { return; } this.ignoreNextMouseUp = false; this.onMenuTriggered(menuIndex, true); e.preventDefault(); e.stopPropagation(); })); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_DOWN, (e) => { if (!this.isOpen) { // Open the menu with mouse down and ignore the following mouse up event this.ignoreNextMouseUp = true; this.onMenuTriggered(menuIndex, true); } else { this.ignoreNextMouseUp = false; } e.preventDefault(); e.stopPropagation(); })); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_UP, (e) => { if (!this.ignoreNextMouseUp) { if (this.isFocused) { this.onMenuTriggered(menuIndex, true); } } else { this.ignoreNextMouseUp = false; } })); this._register(DOM.addDisposableListener(this.customMenus[menuIndex].buttonElement, DOM.EventType.MOUSE_ENTER, () => { if (this.isOpen && !this.isCurrentMenu(menuIndex)) { this.customMenus[menuIndex].buttonElement.focus(); this.cleanupCustomMenu(); this.showCustomMenu(menuIndex, false); } else if (this.isFocused && !this.isOpen) { this.focusedMenu = { index: menuIndex }; this.customMenus[menuIndex].buttonElement.focus(); } })); } } if (firstTimeSetup) { this._register(DOM.addDisposableListener(this.container, DOM.EventType.KEY_DOWN, (e) => { let event = new StandardKeyboardEvent(e as KeyboardEvent); let eventHandled = true; const key = !!e.key ? KeyCodeUtils.fromString(e.key) : KeyCode.Unknown; if (event.equals(KeyCode.LeftArrow) || (event.shiftKey && event.keyCode === KeyCode.Tab)) { this.focusPrevious(); } else if (event.equals(KeyCode.RightArrow) || event.equals(KeyCode.Tab)) { this.focusNext(); } else if (event.equals(KeyCode.Escape) && this.isFocused && !this.isOpen) { this.setUnfocusedState(); } else if (!this.isOpen && !event.ctrlKey && this.currentEnableMenuBarMnemonics && this.mnemonicsInUse && this.mnemonics.has(key)) { const menuIndex = this.mnemonics.get(key); this.onMenuTriggered(menuIndex, false); } else { eventHandled = false; } if (eventHandled) { event.preventDefault(); event.stopPropagation(); } })); this._register(DOM.addDisposableListener(window, DOM.EventType.MOUSE_DOWN, () => { // This mouse event is outside the menubar so it counts as a focus out if (this.isFocused) { this.setUnfocusedState(); } })); this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_IN, (e) => { let event = e as FocusEvent; if (event.relatedTarget) { if (!this.container.contains(event.relatedTarget as HTMLElement)) { this.focusToReturn = event.relatedTarget as HTMLElement; } } })); this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_OUT, (e) => { let event = e as FocusEvent; if (event.relatedTarget) { if (!this.container.contains(event.relatedTarget as HTMLElement)) { this.focusToReturn = null; this.setUnfocusedState(); } } })); this._register(DOM.addDisposableListener(window, DOM.EventType.KEY_DOWN, (e: KeyboardEvent) => { if (!this.currentEnableMenuBarMnemonics || !e.altKey || e.ctrlKey || e.defaultPrevented) { return; } const key = KeyCodeUtils.fromString(e.key); if (!this.mnemonics.has(key)) { return; } // Prevent conflicts with keybindings const standardKeyboardEvent = new StandardKeyboardEvent(e); const resolvedResult = this.keybindingService.softDispatch(standardKeyboardEvent, standardKeyboardEvent.target); if (resolvedResult) { return; } this.mnemonicsInUse = true; this.updateMnemonicVisibility(true); const menuIndex = this.mnemonics.get(key); this.onMenuTriggered(menuIndex, false); })); } } private onMenuTriggered(menuIndex: number, clicked: boolean) { if (this.isOpen) { if (this.isCurrentMenu(menuIndex)) { this.setUnfocusedState(); } else { this.cleanupCustomMenu(); this.showCustomMenu(menuIndex, this.openedViaKeyboard); } } else { this.focusedMenu = { index: menuIndex }; this.openedViaKeyboard = !clicked; this.focusState = MenubarState.OPEN; } } private focusPrevious(): void { if (!this.focusedMenu) { return; } let newFocusedIndex = (this.focusedMenu.index - 1 + this.customMenus.length) % this.customMenus.length; if (newFocusedIndex === this.focusedMenu.index) { return; } if (this.isOpen) { this.cleanupCustomMenu(); this.showCustomMenu(newFocusedIndex); } else if (this.isFocused) { this.focusedMenu.index = newFocusedIndex; this.customMenus[newFocusedIndex].buttonElement.focus(); } } private focusNext(): void { if (!this.focusedMenu) { return; } let newFocusedIndex = (this.focusedMenu.index + 1) % this.customMenus.length; if (newFocusedIndex === this.focusedMenu.index) { return; } if (this.isOpen) { this.cleanupCustomMenu(); this.showCustomMenu(newFocusedIndex); } else if (this.isFocused) { this.focusedMenu.index = newFocusedIndex; this.customMenus[newFocusedIndex].buttonElement.focus(); } } private getMenubarKeybinding(id: string): IMenubarKeybinding { const binding = this.keybindingService.lookupKeybinding(id); if (!binding) { return undefined; } // first try to resolve a native accelerator const electronAccelerator = binding.getElectronAccelerator(); if (electronAccelerator) { return { label: electronAccelerator }; } // we need this fallback to support keybindings that cannot show in electron menus (e.g. chords) const acceleratorLabel = binding.getLabel(); if (acceleratorLabel) { return { label: acceleratorLabel, isNative: false }; } return null; } private populateMenuItems(menu: IMenu, menuToPopulate: IMenubarMenu, keybindings: { [id: string]: IMenubarKeybinding }) { let groups = menu.getActions(); for (let group of groups) { const [, actions] = group; actions.forEach(menuItem => { if (menuItem instanceof SubmenuItemAction) { const submenu = { items: [] }; const menuToDispose = this.menuService.createMenu(menuItem.item.submenu, this.contextKeyService); this.populateMenuItems(menuToDispose, submenu, keybindings); let menubarSubmenuItem: IMenubarMenuItemSubmenu = { id: menuItem.id, label: menuItem.label, submenu: submenu }; menuToPopulate.items.push(menubarSubmenuItem); menuToDispose.dispose(); } else { let menubarMenuItem: IMenubarMenuItemAction = { id: menuItem.id, label: menuItem.label }; if (menuItem.checked) { menubarMenuItem.checked = true; } if (!menuItem.enabled) { menubarMenuItem.enabled = false; } menubarMenuItem.label = this.calculateActionLabel(menubarMenuItem); keybindings[menuItem.id] = this.getMenubarKeybinding(menuItem.id); menuToPopulate.items.push(menubarMenuItem); } }); menuToPopulate.items.push({ id: 'vscode.menubar.separator' }); } if (menuToPopulate.items.length > 0) { menuToPopulate.items.pop(); } } private getAdditionalKeybindings(): { [id: string]: IMenubarKeybinding } { const keybindings = {}; if (isMacintosh) { keybindings['workbench.action.quit'] = (this.getMenubarKeybinding('workbench.action.quit')); } return keybindings; } private getMenubarMenus(menubarData: IMenubarData): boolean { if (!menubarData) { return false; } menubarData.keybindings = this.getAdditionalKeybindings(); for (let topLevelMenuName of Object.keys(this.topLevelMenus)) { const menu = this.topLevelMenus[topLevelMenuName]; let menubarMenu: IMenubarMenu = { items: [] }; this.populateMenuItems(menu, menubarMenu, menubarData.keybindings); if (menubarMenu.items.length === 0) { // Menus are incomplete return false; } menubarData.menus[topLevelMenuName] = menubarMenu; } return true; } private isCurrentMenu(menuIndex: number): boolean { if (!this.focusedMenu) { return false; } return this.focusedMenu.index === menuIndex; } private cleanupCustomMenu(): void { if (this.focusedMenu) { // Remove focus from the menus first this.customMenus[this.focusedMenu.index].buttonElement.focus(); if (this.focusedMenu.holder) { DOM.removeClass(this.focusedMenu.holder.parentElement, 'open'); this.focusedMenu.holder.remove(); } if (this.focusedMenu.widget) { this.focusedMenu.widget.dispose(); } this.focusedMenu = { index: this.focusedMenu.index }; } } private showCustomMenu(menuIndex: number, selectFirst = true): void { const customMenu = this.customMenus[menuIndex]; const menuHolder = $('div.menubar-menu-items-holder'); DOM.addClass(customMenu.buttonElement, 'open'); menuHolder.style.top = `${this.container.clientHeight}px`; menuHolder.style.left = `${customMenu.buttonElement.getBoundingClientRect().left}px`; customMenu.buttonElement.appendChild(menuHolder); let menuOptions: IMenuOptions = { getKeyBinding: (action) => this.keybindingService.lookupKeybinding(action.id), actionRunner: this.actionRunner, enableMnemonics: this.mnemonicsInUse && this.currentEnableMenuBarMnemonics, ariaLabel: customMenu.buttonElement.attributes['aria-label'].value }; let menuWidget = this._register(new Menu(menuHolder, customMenu.actions, menuOptions)); this._register(attachMenuStyler(menuWidget, this.themeService)); this._register(menuWidget.onDidCancel(() => { this.focusState = MenubarState.FOCUSED; })); this._register(menuWidget.onDidBlur(() => { setTimeout(() => { this.cleanupCustomMenu(); }, 100); })); menuWidget.focus(selectFirst); this.focusedMenu = { index: menuIndex, holder: menuHolder, widget: menuWidget }; } public get onVisibilityChange(): Event<boolean> { return this._onVisibilityChange.event; } public get onFocusStateChange(): Event<boolean> { return this._onFocusStateChange.event; } public layout(dimension: DOM.Dimension) { if (this.container) { this.container.style.height = `${dimension.height}px`; } if (!this.isVisible) { this.hideMenubar(); } else { this.showMenubar(); } } public getMenubarItemsDimensions(): DOM.Dimension { if (this.customMenus) { const left = this.customMenus[0].buttonElement.getBoundingClientRect().left; const right = this.customMenus[this.customMenus.length - 1].buttonElement.getBoundingClientRect().right; return new DOM.Dimension(right - left, this.container.clientHeight); } return new DOM.Dimension(0, 0); } public create(parent: HTMLElement): HTMLElement { this.container = parent; // Build the menubar if (this.container) { this.doSetupMenubar(); if (!isMacintosh && this.currentTitlebarStyleSetting === 'custom') { this.setUnfocusedState(); } } return this.container; } } registerThemingParticipant((theme: ITheme, collector: ICssStyleCollector) => { const menubarActiveWindowFgColor = theme.getColor(TITLE_BAR_ACTIVE_FOREGROUND); if (menubarActiveWindowFgColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button { color: ${menubarActiveWindowFgColor}; } `); } const menubarInactiveWindowFgColor = theme.getColor(TITLE_BAR_INACTIVE_FOREGROUND); if (menubarInactiveWindowFgColor) { collector.addRule(` .monaco-workbench .menubar.inactive > .menubar-menu-button { color: ${menubarInactiveWindowFgColor}; } `); } const menubarSelectedFgColor = theme.getColor(MENUBAR_SELECTION_FOREGROUND); if (menubarSelectedFgColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus, .monaco-workbench .menubar:not(:focus-within) > .menubar-menu-button:hover { color: ${menubarSelectedFgColor}; } `); } const menubarSelectedBgColor = theme.getColor(MENUBAR_SELECTION_BACKGROUND); if (menubarSelectedBgColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus, .monaco-workbench .menubar:not(:focus-within) > .menubar-menu-button:hover { background-color: ${menubarSelectedBgColor}; } `); } const menubarSelectedBorderColor = theme.getColor(MENUBAR_SELECTION_BORDER); if (menubarSelectedBorderColor) { collector.addRule(` .monaco-workbench .menubar > .menubar-menu-button:hover { outline: dashed 1px; } .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus { outline: solid 1px; } .monaco-workbench .menubar > .menubar-menu-button.open, .monaco-workbench .menubar > .menubar-menu-button:focus, .monaco-workbench .menubar > .menubar-menu-button:hover { outline-offset: -1px; outline-color: ${menubarSelectedBorderColor}; } `); } }); type ModifierKey = 'alt' | 'ctrl' | 'shift'; interface IModifierKeyStatus { altKey: boolean; shiftKey: boolean; ctrlKey: boolean; lastKeyPressed?: ModifierKey; lastKeyReleased?: ModifierKey; } class ModifierKeyEmitter extends Emitter<IModifierKeyStatus> { private _subscriptions: IDisposable[] = []; private _keyStatus: IModifierKeyStatus; private static instance: ModifierKeyEmitter; private constructor(windowService: IWindowService) { super(); this._keyStatus = { altKey: false, shiftKey: false, ctrlKey: false }; this._subscriptions.push(domEvent(document.body, 'keydown')(e => { const event = new StandardKeyboardEvent(e); if (e.altKey && !this._keyStatus.altKey) { this._keyStatus.lastKeyPressed = 'alt'; } else if (e.ctrlKey && !this._keyStatus.ctrlKey) { this._keyStatus.lastKeyPressed = 'ctrl'; } else if (e.shiftKey && !this._keyStatus.shiftKey) { this._keyStatus.lastKeyPressed = 'shift'; } else if (event.keyCode !== KeyCode.Alt) { this._keyStatus.lastKeyPressed = undefined; } else { return; } this._keyStatus.altKey = e.altKey; this._keyStatus.ctrlKey = e.ctrlKey; this._keyStatus.shiftKey = e.shiftKey; if (this._keyStatus.lastKeyPressed) { this.fire(this._keyStatus); } })); this._subscriptions.push(domEvent(document.body, 'keyup')(e => { if (!e.altKey && this._keyStatus.altKey) { this._keyStatus.lastKeyReleased = 'alt'; } else if (!e.ctrlKey && this._keyStatus.ctrlKey) { this._keyStatus.lastKeyReleased = 'ctrl'; } else if (!e.shiftKey && this._keyStatus.shiftKey) { this._keyStatus.lastKeyReleased = 'shift'; } else { this._keyStatus.lastKeyReleased = undefined; } if (this._keyStatus.lastKeyPressed !== this._keyStatus.lastKeyReleased) { this._keyStatus.lastKeyPressed = undefined; } this._keyStatus.altKey = e.altKey; this._keyStatus.ctrlKey = e.ctrlKey; this._keyStatus.shiftKey = e.shiftKey; if (this._keyStatus.lastKeyReleased) { this.fire(this._keyStatus); } })); this._subscriptions.push(domEvent(document.body, 'mousedown')(e => { this._keyStatus.lastKeyPressed = undefined; })); this._subscriptions.push(windowService.onDidChangeFocus(focused => { if (!focused) { this._keyStatus.lastKeyPressed = undefined; this._keyStatus.lastKeyReleased = undefined; this._keyStatus.altKey = false; this._keyStatus.shiftKey = false; this._keyStatus.shiftKey = false; this.fire(this._keyStatus); } })); } static getInstance(windowService: IWindowService) { if (!ModifierKeyEmitter.instance) { ModifierKeyEmitter.instance = new ModifierKeyEmitter(windowService); } return ModifierKeyEmitter.instance; } dispose() { super.dispose(); this._subscriptions = dispose(this._subscriptions); } }
src/vs/workbench/browser/parts/titlebar/menubarControl.ts
1
https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535
[ 0.998238205909729, 0.12057550251483917, 0.0001636412343941629, 0.00018020797870121896, 0.32040277123451233 ]
{ "id": 1, "code_window": [ "\t\t\tconst cleanMenuLabel = cleanMnemonic(this.topLevelTitles[menuTitle]);\n", "\n", "\t\t\t// Create the top level menu button element\n", "\t\t\tif (firstTimeSetup) {\n", "\n", "\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': 0, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n", "\t\t\t\tconst titleElement = $('div.menubar-menu-title', { 'role': 'none', 'aria-hidden': true });\n", "\n", "\t\t\t\tbuttonElement.appendChild(titleElement);\n", "\t\t\t\tthis.container.appendChild(buttonElement);\n", "\n" ], "labels": [ "keep", "keep", "keep", "keep", "keep", "replace", "keep", "keep", "keep", "keep", "keep" ], "after_edit": [ "\t\t\t\tconst buttonElement = $('div.menubar-menu-button', { 'role': 'menuitem', 'tabindex': -1, 'aria-label': cleanMenuLabel, 'aria-haspopup': true });\n" ], "file_path": "src/vs/workbench/browser/parts/titlebar/menubarControl.ts", "type": "replace", "edit_start_line_idx": 700 }
{ "extends": "../shared.tsconfig.json", "compilerOptions": { "outDir": "./out" }, "include": [ "src/**/*" ] }
extensions/vscode-colorize-tests/tsconfig.json
0
https://github.com/microsoft/vscode/commit/f80c92964ff7e6a46609237664881c7147408535
[ 0.00017211143858730793, 0.00017211143858730793, 0.00017211143858730793, 0.00017211143858730793, 0 ]