"use strict";
(self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] = self["webpackChunk_JUPYTERLAB_CORE_OUTPUT"] || []).push([[417],{
/***/ 20417:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
Accordion: () => (/* reexport */ JupyterAccordion),
AccordionItem: () => (/* reexport */ JupyterAccordionItem),
Anchor: () => (/* reexport */ JupyterAnchor),
AnchoredRegion: () => (/* reexport */ JupyterAnchoredRegion),
Avatar: () => (/* reexport */ JupyterAvatar),
Badge: () => (/* reexport */ JupyterBadge),
Breadcrumb: () => (/* reexport */ JupyterBreadcrumb),
BreadcrumbItem: () => (/* reexport */ JupyterBreadcrumbItem),
Button: () => (/* reexport */ JupyterButton),
Card: () => (/* reexport */ JupyterCard),
Checkbox: () => (/* reexport */ JupyterCheckbox),
Combobox: () => (/* reexport */ JupyterCombobox),
DataGrid: () => (/* reexport */ JupyterDataGrid),
DataGridCell: () => (/* reexport */ JupyterDataGridCell),
DataGridRow: () => (/* reexport */ JupyterDataGridRow),
DateField: () => (/* reexport */ DateField),
DelegatesARIAToolbar: () => (/* reexport */ DelegatesARIAToolbar),
DesignSystemProvider: () => (/* reexport */ DesignSystemProvider),
Dialog: () => (/* reexport */ JupyterDialog),
DirectionalStyleSheetBehavior: () => (/* reexport */ DirectionalStyleSheetBehavior),
Disclosure: () => (/* reexport */ JupyterDisclosure),
Divider: () => (/* reexport */ JupyterDivider),
FoundationToolbar: () => (/* reexport */ FoundationToolbar),
Listbox: () => (/* reexport */ JupyterListbox),
Menu: () => (/* reexport */ JupyterMenu),
MenuItem: () => (/* reexport */ JupyterMenuItem),
NumberField: () => (/* reexport */ JupyterNumberField),
Option: () => (/* reexport */ JupyterOption),
PaletteRGB: () => (/* reexport */ PaletteRGB),
Picker: () => (/* reexport */ JupyterPicker),
PickerList: () => (/* reexport */ JupyterPickerList),
PickerListItem: () => (/* reexport */ JupyterPickerListItem),
PickerMenu: () => (/* reexport */ JupyterPickerMenu),
PickerMenuOption: () => (/* reexport */ JupyterPickerMenuOption),
Progress: () => (/* reexport */ JupyterProgress),
ProgressRing: () => (/* reexport */ JupyterProgressRing),
Radio: () => (/* reexport */ JupyterRadio),
RadioGroup: () => (/* reexport */ JupyterRadioGroup),
Search: () => (/* reexport */ JupyterSearch),
Select: () => (/* reexport */ JupyterSelect),
Skeleton: () => (/* reexport */ JupyterSkeleton),
Slider: () => (/* reexport */ JupyterSlider),
SliderLabel: () => (/* reexport */ JupyterSliderLabel),
StandardLuminance: () => (/* reexport */ StandardLuminance),
SwatchRGB: () => (/* reexport */ SwatchRGB),
Switch: () => (/* reexport */ JupyterSwitch),
Tab: () => (/* reexport */ JupyterTab),
TabPanel: () => (/* reexport */ JupyterTabPanel),
Tabs: () => (/* reexport */ JupyterTabs),
TextArea: () => (/* reexport */ JupyterTextArea),
TextField: () => (/* reexport */ JupyterTextField),
Toolbar: () => (/* reexport */ Toolbar),
Tooltip: () => (/* reexport */ JupyterTooltip),
TreeItem: () => (/* reexport */ JupyterTreeItem),
TreeView: () => (/* reexport */ JupyterTreeView),
accentColor: () => (/* reexport */ accentColor),
accentFillActive: () => (/* reexport */ accentFillActive),
accentFillActiveDelta: () => (/* reexport */ accentFillActiveDelta),
accentFillFocus: () => (/* reexport */ accentFillFocus),
accentFillFocusDelta: () => (/* reexport */ accentFillFocusDelta),
accentFillHover: () => (/* reexport */ accentFillHover),
accentFillHoverDelta: () => (/* reexport */ accentFillHoverDelta),
accentFillRecipe: () => (/* reexport */ accentFillRecipe),
accentFillRest: () => (/* reexport */ accentFillRest),
accentFillRestDelta: () => (/* reexport */ accentFillRestDelta),
accentForegroundActive: () => (/* reexport */ accentForegroundActive),
accentForegroundActiveDelta: () => (/* reexport */ accentForegroundActiveDelta),
accentForegroundFocus: () => (/* reexport */ accentForegroundFocus),
accentForegroundFocusDelta: () => (/* reexport */ accentForegroundFocusDelta),
accentForegroundHover: () => (/* reexport */ accentForegroundHover),
accentForegroundHoverDelta: () => (/* reexport */ accentForegroundHoverDelta),
accentForegroundRecipe: () => (/* reexport */ accentForegroundRecipe),
accentForegroundRest: () => (/* reexport */ accentForegroundRest),
accentForegroundRestDelta: () => (/* reexport */ accentForegroundRestDelta),
accentPalette: () => (/* reexport */ accentPalette),
accordionItemStyles: () => (/* reexport */ accordionItemStyles),
accordionStyles: () => (/* reexport */ accordionStyles),
addJupyterLabThemeChangeListener: () => (/* reexport */ addJupyterLabThemeChangeListener),
allComponents: () => (/* reexport */ allComponents),
anchorStyles: () => (/* reexport */ anchorStyles),
anchoredRegionStyles: () => (/* reexport */ anchoredRegionStyles),
applyJupyterTheme: () => (/* reexport */ applyJupyterTheme),
avatarStyles: () => (/* reexport */ avatarStyles),
badgeStyles: () => (/* reexport */ badgeStyles),
baseHeightMultiplier: () => (/* reexport */ baseHeightMultiplier),
baseHorizontalSpacingMultiplier: () => (/* reexport */ baseHorizontalSpacingMultiplier),
baseLayerLuminance: () => (/* reexport */ baseLayerLuminance),
bodyFont: () => (/* reexport */ bodyFont),
breadcrumbItemStyles: () => (/* reexport */ breadcrumbItemStyles),
breadcrumbStyles: () => (/* reexport */ breadcrumbStyles),
buttonStyles: () => (/* reexport */ buttonStyles),
cardStyles: () => (/* reexport */ cardStyles),
checkboxStyles: () => (/* reexport */ checkboxStyles),
checkboxTemplate: () => (/* reexport */ checkboxTemplate),
comboboxStyles: () => (/* reexport */ comboboxStyles),
controlCornerRadius: () => (/* reexport */ controlCornerRadius),
dataGridCellStyles: () => (/* reexport */ dataGridCellStyles),
dataGridRowStyles: () => (/* reexport */ dataGridRowStyles),
dataGridStyles: () => (/* reexport */ dataGridStyles),
dateFieldStyles: () => (/* reexport */ dateFieldStyles),
dateFieldTemplate: () => (/* reexport */ dateFieldTemplate),
density: () => (/* reexport */ density),
designSystemProviderStyles: () => (/* reexport */ designSystemProviderStyles),
designSystemProviderTemplate: () => (/* reexport */ designSystemProviderTemplate),
designUnit: () => (/* reexport */ designUnit),
dialogStyles: () => (/* reexport */ dialogStyles),
direction: () => (/* reexport */ direction),
disabledOpacity: () => (/* reexport */ disabledOpacity),
disclosureStyles: () => (/* reexport */ disclosureStyles),
dividerStyles: () => (/* reexport */ dividerStyles),
elementScale: () => (/* reexport */ elementScale),
errorColor: () => (/* reexport */ errorColor),
errorFillActive: () => (/* reexport */ errorFillActive),
errorFillFocus: () => (/* reexport */ errorFillFocus),
errorFillHover: () => (/* reexport */ errorFillHover),
errorFillRecipe: () => (/* reexport */ errorFillRecipe),
errorFillRest: () => (/* reexport */ errorFillRest),
errorForegroundActive: () => (/* reexport */ errorForegroundActive),
errorForegroundFocus: () => (/* reexport */ errorForegroundFocus),
errorForegroundHover: () => (/* reexport */ errorForegroundHover),
errorForegroundRecipe: () => (/* reexport */ errorForegroundRecipe),
errorForegroundRest: () => (/* reexport */ errorForegroundRest),
errorPalette: () => (/* reexport */ errorPalette),
fillColor: () => (/* reexport */ fillColor),
focusStrokeInner: () => (/* reexport */ design_tokens_focusStrokeInner),
focusStrokeInnerRecipe: () => (/* reexport */ focusStrokeInnerRecipe),
focusStrokeOuter: () => (/* reexport */ design_tokens_focusStrokeOuter),
focusStrokeOuterRecipe: () => (/* reexport */ focusStrokeOuterRecipe),
focusStrokeWidth: () => (/* reexport */ focusStrokeWidth),
foregroundOnAccentActive: () => (/* reexport */ foregroundOnAccentActive),
foregroundOnAccentActiveLarge: () => (/* reexport */ foregroundOnAccentActiveLarge),
foregroundOnAccentFocus: () => (/* reexport */ foregroundOnAccentFocus),
foregroundOnAccentFocusLarge: () => (/* reexport */ foregroundOnAccentFocusLarge),
foregroundOnAccentHover: () => (/* reexport */ foregroundOnAccentHover),
foregroundOnAccentHoverLarge: () => (/* reexport */ foregroundOnAccentHoverLarge),
foregroundOnAccentLargeRecipe: () => (/* reexport */ foregroundOnAccentLargeRecipe),
foregroundOnAccentRecipe: () => (/* reexport */ foregroundOnAccentRecipe),
foregroundOnAccentRest: () => (/* reexport */ foregroundOnAccentRest),
foregroundOnAccentRestLarge: () => (/* reexport */ foregroundOnAccentRestLarge),
foregroundOnErrorActive: () => (/* reexport */ foregroundOnErrorActive),
foregroundOnErrorActiveLarge: () => (/* reexport */ foregroundOnErrorActiveLarge),
foregroundOnErrorFocus: () => (/* reexport */ foregroundOnErrorFocus),
foregroundOnErrorFocusLarge: () => (/* reexport */ foregroundOnErrorFocusLarge),
foregroundOnErrorHover: () => (/* reexport */ foregroundOnErrorHover),
foregroundOnErrorHoverLarge: () => (/* reexport */ foregroundOnErrorHoverLarge),
foregroundOnErrorLargeRecipe: () => (/* reexport */ foregroundOnErrorLargeRecipe),
foregroundOnErrorRecipe: () => (/* reexport */ foregroundOnErrorRecipe),
foregroundOnErrorRest: () => (/* reexport */ foregroundOnErrorRest),
foregroundOnErrorRestLarge: () => (/* reexport */ foregroundOnErrorRestLarge),
heightNumberAsToken: () => (/* reexport */ heightNumberAsToken),
horizontalSliderLabelStyles: () => (/* reexport */ horizontalSliderLabelStyles),
imgTemplate: () => (/* reexport */ imgTemplate),
isDark: () => (/* reexport */ isDark),
jpAccordion: () => (/* reexport */ jpAccordion),
jpAccordionItem: () => (/* reexport */ jpAccordionItem),
jpAnchor: () => (/* reexport */ jpAnchor),
jpAnchoredRegion: () => (/* reexport */ jpAnchoredRegion),
jpAvatar: () => (/* reexport */ jpAvatar),
jpBadge: () => (/* reexport */ jpBadge),
jpBreadcrumb: () => (/* reexport */ jpBreadcrumb),
jpBreadcrumbItem: () => (/* reexport */ jpBreadcrumbItem),
jpButton: () => (/* reexport */ jpButton),
jpCard: () => (/* reexport */ jpCard),
jpCheckbox: () => (/* reexport */ jpCheckbox),
jpCombobox: () => (/* reexport */ jpCombobox),
jpDataGrid: () => (/* reexport */ jpDataGrid),
jpDataGridCell: () => (/* reexport */ jpDataGridCell),
jpDataGridRow: () => (/* reexport */ jpDataGridRow),
jpDateField: () => (/* reexport */ jpDateField),
jpDesignSystemProvider: () => (/* reexport */ jpDesignSystemProvider),
jpDialog: () => (/* reexport */ jpDialog),
jpDisclosure: () => (/* reexport */ jpDisclosure),
jpDivider: () => (/* reexport */ jpDivider),
jpListbox: () => (/* reexport */ jpListbox),
jpMenu: () => (/* reexport */ jpMenu),
jpMenuItem: () => (/* reexport */ jpMenuItem),
jpNumberField: () => (/* reexport */ jpNumberField),
jpOption: () => (/* reexport */ jpOption),
jpPicker: () => (/* reexport */ jpPicker),
jpPickerList: () => (/* reexport */ jpPickerList),
jpPickerListItem: () => (/* reexport */ jpPickerListItem),
jpPickerMenu: () => (/* reexport */ jpPickerMenu),
jpPickerMenuOption: () => (/* reexport */ jpPickerMenuOption),
jpProgress: () => (/* reexport */ jpProgress),
jpProgressRing: () => (/* reexport */ jpProgressRing),
jpRadio: () => (/* reexport */ jpRadio),
jpRadioGroup: () => (/* reexport */ jpRadioGroup),
jpSearch: () => (/* reexport */ jpSearch),
jpSelect: () => (/* reexport */ jpSelect),
jpSkeleton: () => (/* reexport */ jpSkeleton),
jpSlider: () => (/* reexport */ jpSlider),
jpSliderLabel: () => (/* reexport */ jpSliderLabel),
jpSwitch: () => (/* reexport */ jpSwitch),
jpTab: () => (/* reexport */ jpTab),
jpTabPanel: () => (/* reexport */ jpTabPanel),
jpTabs: () => (/* reexport */ jpTabs),
jpTextArea: () => (/* reexport */ jpTextArea),
jpTextField: () => (/* reexport */ jpTextField),
jpToolbar: () => (/* reexport */ jpToolbar),
jpTooltip: () => (/* reexport */ jpTooltip),
jpTreeItem: () => (/* reexport */ jpTreeItem),
jpTreeView: () => (/* reexport */ jpTreeView),
listboxStyles: () => (/* reexport */ listboxStyles),
menuItemStyles: () => (/* reexport */ menuItemStyles),
menuStyles: () => (/* reexport */ menuStyles),
neutralColor: () => (/* reexport */ neutralColor),
neutralFillActive: () => (/* reexport */ neutralFillActive),
neutralFillActiveDelta: () => (/* reexport */ neutralFillActiveDelta),
neutralFillFocus: () => (/* reexport */ neutralFillFocus),
neutralFillFocusDelta: () => (/* reexport */ neutralFillFocusDelta),
neutralFillHover: () => (/* reexport */ neutralFillHover),
neutralFillHoverDelta: () => (/* reexport */ neutralFillHoverDelta),
neutralFillInputActive: () => (/* reexport */ neutralFillInputActive),
neutralFillInputActiveDelta: () => (/* reexport */ neutralFillInputActiveDelta),
neutralFillInputFocus: () => (/* reexport */ neutralFillInputFocus),
neutralFillInputFocusDelta: () => (/* reexport */ neutralFillInputFocusDelta),
neutralFillInputHover: () => (/* reexport */ neutralFillInputHover),
neutralFillInputHoverDelta: () => (/* reexport */ neutralFillInputHoverDelta),
neutralFillInputRecipe: () => (/* reexport */ neutralFillInputRecipe),
neutralFillInputRest: () => (/* reexport */ neutralFillInputRest),
neutralFillInputRestDelta: () => (/* reexport */ neutralFillInputRestDelta),
neutralFillLayerRecipe: () => (/* reexport */ neutralFillLayerRecipe),
neutralFillLayerRest: () => (/* reexport */ neutralFillLayerRest),
neutralFillLayerRestDelta: () => (/* reexport */ neutralFillLayerRestDelta),
neutralFillRecipe: () => (/* reexport */ neutralFillRecipe),
neutralFillRest: () => (/* reexport */ neutralFillRest),
neutralFillRestDelta: () => (/* reexport */ neutralFillRestDelta),
neutralFillStealthActive: () => (/* reexport */ neutralFillStealthActive),
neutralFillStealthActiveDelta: () => (/* reexport */ neutralFillStealthActiveDelta),
neutralFillStealthFocus: () => (/* reexport */ neutralFillStealthFocus),
neutralFillStealthFocusDelta: () => (/* reexport */ neutralFillStealthFocusDelta),
neutralFillStealthHover: () => (/* reexport */ neutralFillStealthHover),
neutralFillStealthHoverDelta: () => (/* reexport */ neutralFillStealthHoverDelta),
neutralFillStealthRecipe: () => (/* reexport */ neutralFillStealthRecipe),
neutralFillStealthRest: () => (/* reexport */ neutralFillStealthRest),
neutralFillStealthRestDelta: () => (/* reexport */ neutralFillStealthRestDelta),
neutralFillStrongActive: () => (/* reexport */ neutralFillStrongActive),
neutralFillStrongActiveDelta: () => (/* reexport */ neutralFillStrongActiveDelta),
neutralFillStrongFocus: () => (/* reexport */ neutralFillStrongFocus),
neutralFillStrongFocusDelta: () => (/* reexport */ neutralFillStrongFocusDelta),
neutralFillStrongHover: () => (/* reexport */ neutralFillStrongHover),
neutralFillStrongHoverDelta: () => (/* reexport */ neutralFillStrongHoverDelta),
neutralFillStrongRecipe: () => (/* reexport */ neutralFillStrongRecipe),
neutralFillStrongRest: () => (/* reexport */ neutralFillStrongRest),
neutralFillStrongRestDelta: () => (/* reexport */ neutralFillStrongRestDelta),
neutralForegroundHint: () => (/* reexport */ design_tokens_neutralForegroundHint),
neutralForegroundHintRecipe: () => (/* reexport */ neutralForegroundHintRecipe),
neutralForegroundRecipe: () => (/* reexport */ neutralForegroundRecipe),
neutralForegroundRest: () => (/* reexport */ neutralForegroundRest),
neutralLayer1: () => (/* reexport */ design_tokens_neutralLayer1),
neutralLayer1Recipe: () => (/* reexport */ neutralLayer1Recipe),
neutralLayer2: () => (/* reexport */ design_tokens_neutralLayer2),
neutralLayer2Recipe: () => (/* reexport */ neutralLayer2Recipe),
neutralLayer3: () => (/* reexport */ design_tokens_neutralLayer3),
neutralLayer3Recipe: () => (/* reexport */ neutralLayer3Recipe),
neutralLayer4: () => (/* reexport */ design_tokens_neutralLayer4),
neutralLayer4Recipe: () => (/* reexport */ neutralLayer4Recipe),
neutralLayerCardContainer: () => (/* reexport */ design_tokens_neutralLayerCardContainer),
neutralLayerCardContainerRecipe: () => (/* reexport */ neutralLayerCardContainerRecipe),
neutralLayerFloating: () => (/* reexport */ design_tokens_neutralLayerFloating),
neutralLayerFloatingRecipe: () => (/* reexport */ neutralLayerFloatingRecipe),
neutralPalette: () => (/* reexport */ neutralPalette),
neutralStrokeActive: () => (/* reexport */ neutralStrokeActive),
neutralStrokeActiveDelta: () => (/* reexport */ neutralStrokeActiveDelta),
neutralStrokeDividerRecipe: () => (/* reexport */ neutralStrokeDividerRecipe),
neutralStrokeDividerRest: () => (/* reexport */ neutralStrokeDividerRest),
neutralStrokeDividerRestDelta: () => (/* reexport */ neutralStrokeDividerRestDelta),
neutralStrokeFocus: () => (/* reexport */ neutralStrokeFocus),
neutralStrokeFocusDelta: () => (/* reexport */ neutralStrokeFocusDelta),
neutralStrokeHover: () => (/* reexport */ neutralStrokeHover),
neutralStrokeHoverDelta: () => (/* reexport */ neutralStrokeHoverDelta),
neutralStrokeRecipe: () => (/* reexport */ neutralStrokeRecipe),
neutralStrokeRest: () => (/* reexport */ neutralStrokeRest),
neutralStrokeRestDelta: () => (/* reexport */ neutralStrokeRestDelta),
numberFieldStyles: () => (/* reexport */ numberFieldStyles),
optionStyles: () => (/* reexport */ optionStyles),
pickerListItemStyles: () => (/* reexport */ pickerListItemStyles),
pickerMenuOptionStyles: () => (/* reexport */ pickerMenuOptionStyles),
pickerMenuStyles: () => (/* reexport */ pickerMenuStyles),
pickerStyles: () => (/* reexport */ pickerStyles),
progressRingStyles: () => (/* reexport */ progressRingStyles),
progressStyles: () => (/* reexport */ progressStyles),
provideJupyterDesignSystem: () => (/* reexport */ provideJupyterDesignSystem),
radioGroupStyles: () => (/* reexport */ radioGroupStyles),
radioStyles: () => (/* reexport */ radioStyles),
radioTemplate: () => (/* reexport */ radioTemplate),
searchStyles: () => (/* reexport */ searchStyles),
selectStyles: () => (/* reexport */ selectStyles),
skeletonStyles: () => (/* reexport */ skeletonStyles),
sliderLabelStyles: () => (/* reexport */ sliderLabelStyles),
sliderStyles: () => (/* reexport */ sliderStyles),
strokeWidth: () => (/* reexport */ strokeWidth),
switchStyles: () => (/* reexport */ switchStyles),
tabPanelStyles: () => (/* reexport */ tabPanelStyles),
tabStyles: () => (/* reexport */ tabStyles),
tabsStyles: () => (/* reexport */ tabsStyles),
textAreaStyles: () => (/* reexport */ textAreaStyles),
textFieldStyles: () => (/* reexport */ textFieldStyles),
toolbarStyles: () => (/* reexport */ toolbarStyles),
tooltipStyles: () => (/* reexport */ tooltipStyles),
treeItemStyles: () => (/* reexport */ treeItemStyles),
treeViewStyles: () => (/* reexport */ treeViewStyles),
typeRampBaseFontSize: () => (/* reexport */ typeRampBaseFontSize),
typeRampBaseLineHeight: () => (/* reexport */ typeRampBaseLineHeight),
typeRampMinus1FontSize: () => (/* reexport */ typeRampMinus1FontSize),
typeRampMinus1LineHeight: () => (/* reexport */ typeRampMinus1LineHeight),
typeRampMinus2FontSize: () => (/* reexport */ typeRampMinus2FontSize),
typeRampMinus2LineHeight: () => (/* reexport */ typeRampMinus2LineHeight),
typeRampPlus1FontSize: () => (/* reexport */ typeRampPlus1FontSize),
typeRampPlus1LineHeight: () => (/* reexport */ typeRampPlus1LineHeight),
typeRampPlus2FontSize: () => (/* reexport */ typeRampPlus2FontSize),
typeRampPlus2LineHeight: () => (/* reexport */ typeRampPlus2LineHeight),
typeRampPlus3FontSize: () => (/* reexport */ typeRampPlus3FontSize),
typeRampPlus3LineHeight: () => (/* reexport */ typeRampPlus3LineHeight),
typeRampPlus4FontSize: () => (/* reexport */ typeRampPlus4FontSize),
typeRampPlus4LineHeight: () => (/* reexport */ typeRampPlus4LineHeight),
typeRampPlus5FontSize: () => (/* reexport */ typeRampPlus5FontSize),
typeRampPlus5LineHeight: () => (/* reexport */ typeRampPlus5LineHeight),
typeRampPlus6FontSize: () => (/* reexport */ typeRampPlus6FontSize),
typeRampPlus6LineHeight: () => (/* reexport */ typeRampPlus6LineHeight),
verticalSliderLabelStyles: () => (/* reexport */ verticalSliderLabelStyles)
});
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/math-utilities.js
/**
* Ensures that an input number does not exceed a max value and is not less than a min value.
* @param i - the number to clamp
* @param min - the maximum (inclusive) value
* @param max - the minimum (inclusive) value
* @public
*/
function clamp(i, min, max) {
if (isNaN(i) || i <= min) {
return min;
}
else if (i >= max) {
return max;
}
return i;
}
/**
* Scales an input to a number between 0 and 1
* @param i - a number between min and max
* @param min - the max value
* @param max - the min value
* @public
*/
function math_utilities_normalize(i, min, max) {
if (isNaN(i) || i <= min) {
return 0.0;
}
else if (i >= max) {
return 1.0;
}
return i / (max - min);
}
/**
* Scales a number between 0 and 1
* @param i - the number to denormalize
* @param min - the min value
* @param max - the max value
* @public
*/
function denormalize(i, min, max) {
if (isNaN(i)) {
return min;
}
return min + i * (max - min);
}
/**
* Converts degrees to radians.
* @param i - degrees
* @public
*/
function degreesToRadians(i) {
return i * (Math.PI / 180.0);
}
/**
* Converts radians to degrees.
* @param i - radians
* @public
*/
function radiansToDegrees(i) {
return i * (180.0 / Math.PI);
}
/**
* Converts a number between 0 and 255 to a hex string.
* @param i - the number to convert to a hex string
* @public
*/
function getHexStringForByte(i) {
const s = Math.round(clamp(i, 0.0, 255.0)).toString(16);
if (s.length === 1) {
return "0" + s;
}
return s;
}
/**
* Linearly interpolate
* @public
*/
function lerp(i, min, max) {
if (isNaN(i) || i <= 0.0) {
return min;
}
else if (i >= 1.0) {
return max;
}
return min + i * (max - min);
}
/**
* Linearly interpolate angles in degrees
* @public
*/
function lerpAnglesInDegrees(i, min, max) {
if (i <= 0.0) {
return min % 360.0;
}
else if (i >= 1.0) {
return max % 360.0;
}
const a = (min - max + 360.0) % 360.0;
const b = (max - min + 360.0) % 360.0;
if (a <= b) {
return (min - a * i + 360.0) % 360.0;
}
return (min + a * i + 360.0) % 360.0;
}
const TwoPI = Math.PI * 2;
/**
* Linearly interpolate angles in radians
* @public
*/
function lerpAnglesInRadians(i, min, max) {
if (isNaN(i) || i <= 0.0) {
return min % TwoPI;
}
else if (i >= 1.0) {
return max % TwoPI;
}
const a = (min - max + TwoPI) % TwoPI;
const b = (max - min + TwoPI) % TwoPI;
if (a <= b) {
return (min - a * i + TwoPI) % TwoPI;
}
return (min + a * i + TwoPI) % TwoPI;
}
/**
*
* Will return infinity if i*10^(precision) overflows number
* note that floating point rounding rules come into play here
* so values that end up rounding on a .5 round to the nearest
* even not always up so 2.5 rounds to 2
* @param i - the number to round
* @param precision - the precision to round to
*
* @public
*/
function roundToPrecisionSmall(i, precision) {
const factor = Math.pow(10, precision);
return Math.round(i * factor) / factor;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-rgba-64.js
/**
* A RGBA color with 64 bit channels.
*
* @example
* ```ts
* new ColorRGBA64(1, 0, 0, 1) // red
* ```
* @public
*/
class color_rgba_64_ColorRGBA64 {
/**
*
* @param red - the red value
* @param green - the green value
* @param blue - the blue value
* @param alpha - the alpha value
*/
constructor(red, green, blue, alpha) {
this.r = red;
this.g = green;
this.b = blue;
this.a = typeof alpha === "number" && !isNaN(alpha) ? alpha : 1;
}
/**
* Construct a {@link ColorRGBA64} from a {@link ColorRGBA64Config}
* @param data - the config object
*/
static fromObject(data) {
return data && !isNaN(data.r) && !isNaN(data.g) && !isNaN(data.b)
? new color_rgba_64_ColorRGBA64(data.r, data.g, data.b, data.a)
: null;
}
/**
* Determines if one color is equal to another.
* @param rhs - the color to compare
*/
equalValue(rhs) {
return (this.r === rhs.r && this.g === rhs.g && this.b === rhs.b && this.a === rhs.a);
}
/**
* Returns the color formatted as a string; #RRGGBB
*/
toStringHexRGB() {
return "#" + [this.r, this.g, this.b].map(this.formatHexValue).join("");
}
/**
* Returns the color formatted as a string; #RRGGBBAA
*/
toStringHexRGBA() {
return this.toStringHexRGB() + this.formatHexValue(this.a);
}
/**
* Returns the color formatted as a string; #AARRGGBB
*/
toStringHexARGB() {
return "#" + [this.a, this.r, this.g, this.b].map(this.formatHexValue).join("");
}
/**
* Returns the color formatted as a string; "rgb(0xRR, 0xGG, 0xBB)"
*/
toStringWebRGB() {
return `rgb(${Math.round(denormalize(this.r, 0.0, 255.0))},${Math.round(denormalize(this.g, 0.0, 255.0))},${Math.round(denormalize(this.b, 0.0, 255.0))})`;
}
/**
* Returns the color formatted as a string; "rgba(0xRR, 0xGG, 0xBB, a)"
* @remarks
* Note that this follows the convention of putting alpha in the range [0.0,1.0] while the other three channels are [0,255]
*/
toStringWebRGBA() {
return `rgba(${Math.round(denormalize(this.r, 0.0, 255.0))},${Math.round(denormalize(this.g, 0.0, 255.0))},${Math.round(denormalize(this.b, 0.0, 255.0))},${clamp(this.a, 0, 1)})`;
}
/**
* Returns a new {@link ColorRGBA64} rounded to the provided precision
* @param precision - the precision to round to
*/
roundToPrecision(precision) {
return new color_rgba_64_ColorRGBA64(roundToPrecisionSmall(this.r, precision), roundToPrecisionSmall(this.g, precision), roundToPrecisionSmall(this.b, precision), roundToPrecisionSmall(this.a, precision));
}
/**
* Returns a new {@link ColorRGBA64} with channel values clamped between 0 and 1.
*/
clamp() {
return new color_rgba_64_ColorRGBA64(clamp(this.r, 0, 1), clamp(this.g, 0, 1), clamp(this.b, 0, 1), clamp(this.a, 0, 1));
}
/**
* Converts the {@link ColorRGBA64} to a {@link ColorRGBA64Config}.
*/
toObject() {
return { r: this.r, g: this.g, b: this.b, a: this.a };
}
formatHexValue(value) {
return getHexStringForByte(denormalize(value, 0.0, 255.0));
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/named-colors.js
const namedColorsConfigs = {
aliceblue: {
r: 0.941176,
g: 0.972549,
b: 1,
},
antiquewhite: {
r: 0.980392,
g: 0.921569,
b: 0.843137,
},
aqua: {
r: 0,
g: 1,
b: 1,
},
aquamarine: {
r: 0.498039,
g: 1,
b: 0.831373,
},
azure: {
r: 0.941176,
g: 1,
b: 1,
},
beige: {
r: 0.960784,
g: 0.960784,
b: 0.862745,
},
bisque: {
r: 1,
g: 0.894118,
b: 0.768627,
},
black: {
r: 0,
g: 0,
b: 0,
},
blanchedalmond: {
r: 1,
g: 0.921569,
b: 0.803922,
},
blue: {
r: 0,
g: 0,
b: 1,
},
blueviolet: {
r: 0.541176,
g: 0.168627,
b: 0.886275,
},
brown: {
r: 0.647059,
g: 0.164706,
b: 0.164706,
},
burlywood: {
r: 0.870588,
g: 0.721569,
b: 0.529412,
},
cadetblue: {
r: 0.372549,
g: 0.619608,
b: 0.627451,
},
chartreuse: {
r: 0.498039,
g: 1,
b: 0,
},
chocolate: {
r: 0.823529,
g: 0.411765,
b: 0.117647,
},
coral: {
r: 1,
g: 0.498039,
b: 0.313725,
},
cornflowerblue: {
r: 0.392157,
g: 0.584314,
b: 0.929412,
},
cornsilk: {
r: 1,
g: 0.972549,
b: 0.862745,
},
crimson: {
r: 0.862745,
g: 0.078431,
b: 0.235294,
},
cyan: {
r: 0,
g: 1,
b: 1,
},
darkblue: {
r: 0,
g: 0,
b: 0.545098,
},
darkcyan: {
r: 0,
g: 0.545098,
b: 0.545098,
},
darkgoldenrod: {
r: 0.721569,
g: 0.52549,
b: 0.043137,
},
darkgray: {
r: 0.662745,
g: 0.662745,
b: 0.662745,
},
darkgreen: {
r: 0,
g: 0.392157,
b: 0,
},
darkgrey: {
r: 0.662745,
g: 0.662745,
b: 0.662745,
},
darkkhaki: {
r: 0.741176,
g: 0.717647,
b: 0.419608,
},
darkmagenta: {
r: 0.545098,
g: 0,
b: 0.545098,
},
darkolivegreen: {
r: 0.333333,
g: 0.419608,
b: 0.184314,
},
darkorange: {
r: 1,
g: 0.54902,
b: 0,
},
darkorchid: {
r: 0.6,
g: 0.196078,
b: 0.8,
},
darkred: {
r: 0.545098,
g: 0,
b: 0,
},
darksalmon: {
r: 0.913725,
g: 0.588235,
b: 0.478431,
},
darkseagreen: {
r: 0.560784,
g: 0.737255,
b: 0.560784,
},
darkslateblue: {
r: 0.282353,
g: 0.239216,
b: 0.545098,
},
darkslategray: {
r: 0.184314,
g: 0.309804,
b: 0.309804,
},
darkslategrey: {
r: 0.184314,
g: 0.309804,
b: 0.309804,
},
darkturquoise: {
r: 0,
g: 0.807843,
b: 0.819608,
},
darkviolet: {
r: 0.580392,
g: 0,
b: 0.827451,
},
deeppink: {
r: 1,
g: 0.078431,
b: 0.576471,
},
deepskyblue: {
r: 0,
g: 0.74902,
b: 1,
},
dimgray: {
r: 0.411765,
g: 0.411765,
b: 0.411765,
},
dimgrey: {
r: 0.411765,
g: 0.411765,
b: 0.411765,
},
dodgerblue: {
r: 0.117647,
g: 0.564706,
b: 1,
},
firebrick: {
r: 0.698039,
g: 0.133333,
b: 0.133333,
},
floralwhite: {
r: 1,
g: 0.980392,
b: 0.941176,
},
forestgreen: {
r: 0.133333,
g: 0.545098,
b: 0.133333,
},
fuchsia: {
r: 1,
g: 0,
b: 1,
},
gainsboro: {
r: 0.862745,
g: 0.862745,
b: 0.862745,
},
ghostwhite: {
r: 0.972549,
g: 0.972549,
b: 1,
},
gold: {
r: 1,
g: 0.843137,
b: 0,
},
goldenrod: {
r: 0.854902,
g: 0.647059,
b: 0.12549,
},
gray: {
r: 0.501961,
g: 0.501961,
b: 0.501961,
},
green: {
r: 0,
g: 0.501961,
b: 0,
},
greenyellow: {
r: 0.678431,
g: 1,
b: 0.184314,
},
grey: {
r: 0.501961,
g: 0.501961,
b: 0.501961,
},
honeydew: {
r: 0.941176,
g: 1,
b: 0.941176,
},
hotpink: {
r: 1,
g: 0.411765,
b: 0.705882,
},
indianred: {
r: 0.803922,
g: 0.360784,
b: 0.360784,
},
indigo: {
r: 0.294118,
g: 0,
b: 0.509804,
},
ivory: {
r: 1,
g: 1,
b: 0.941176,
},
khaki: {
r: 0.941176,
g: 0.901961,
b: 0.54902,
},
lavender: {
r: 0.901961,
g: 0.901961,
b: 0.980392,
},
lavenderblush: {
r: 1,
g: 0.941176,
b: 0.960784,
},
lawngreen: {
r: 0.486275,
g: 0.988235,
b: 0,
},
lemonchiffon: {
r: 1,
g: 0.980392,
b: 0.803922,
},
lightblue: {
r: 0.678431,
g: 0.847059,
b: 0.901961,
},
lightcoral: {
r: 0.941176,
g: 0.501961,
b: 0.501961,
},
lightcyan: {
r: 0.878431,
g: 1,
b: 1,
},
lightgoldenrodyellow: {
r: 0.980392,
g: 0.980392,
b: 0.823529,
},
lightgray: {
r: 0.827451,
g: 0.827451,
b: 0.827451,
},
lightgreen: {
r: 0.564706,
g: 0.933333,
b: 0.564706,
},
lightgrey: {
r: 0.827451,
g: 0.827451,
b: 0.827451,
},
lightpink: {
r: 1,
g: 0.713725,
b: 0.756863,
},
lightsalmon: {
r: 1,
g: 0.627451,
b: 0.478431,
},
lightseagreen: {
r: 0.12549,
g: 0.698039,
b: 0.666667,
},
lightskyblue: {
r: 0.529412,
g: 0.807843,
b: 0.980392,
},
lightslategray: {
r: 0.466667,
g: 0.533333,
b: 0.6,
},
lightslategrey: {
r: 0.466667,
g: 0.533333,
b: 0.6,
},
lightsteelblue: {
r: 0.690196,
g: 0.768627,
b: 0.870588,
},
lightyellow: {
r: 1,
g: 1,
b: 0.878431,
},
lime: {
r: 0,
g: 1,
b: 0,
},
limegreen: {
r: 0.196078,
g: 0.803922,
b: 0.196078,
},
linen: {
r: 0.980392,
g: 0.941176,
b: 0.901961,
},
magenta: {
r: 1,
g: 0,
b: 1,
},
maroon: {
r: 0.501961,
g: 0,
b: 0,
},
mediumaquamarine: {
r: 0.4,
g: 0.803922,
b: 0.666667,
},
mediumblue: {
r: 0,
g: 0,
b: 0.803922,
},
mediumorchid: {
r: 0.729412,
g: 0.333333,
b: 0.827451,
},
mediumpurple: {
r: 0.576471,
g: 0.439216,
b: 0.858824,
},
mediumseagreen: {
r: 0.235294,
g: 0.701961,
b: 0.443137,
},
mediumslateblue: {
r: 0.482353,
g: 0.407843,
b: 0.933333,
},
mediumspringgreen: {
r: 0,
g: 0.980392,
b: 0.603922,
},
mediumturquoise: {
r: 0.282353,
g: 0.819608,
b: 0.8,
},
mediumvioletred: {
r: 0.780392,
g: 0.082353,
b: 0.521569,
},
midnightblue: {
r: 0.098039,
g: 0.098039,
b: 0.439216,
},
mintcream: {
r: 0.960784,
g: 1,
b: 0.980392,
},
mistyrose: {
r: 1,
g: 0.894118,
b: 0.882353,
},
moccasin: {
r: 1,
g: 0.894118,
b: 0.709804,
},
navajowhite: {
r: 1,
g: 0.870588,
b: 0.678431,
},
navy: {
r: 0,
g: 0,
b: 0.501961,
},
oldlace: {
r: 0.992157,
g: 0.960784,
b: 0.901961,
},
olive: {
r: 0.501961,
g: 0.501961,
b: 0,
},
olivedrab: {
r: 0.419608,
g: 0.556863,
b: 0.137255,
},
orange: {
r: 1,
g: 0.647059,
b: 0,
},
orangered: {
r: 1,
g: 0.270588,
b: 0,
},
orchid: {
r: 0.854902,
g: 0.439216,
b: 0.839216,
},
palegoldenrod: {
r: 0.933333,
g: 0.909804,
b: 0.666667,
},
palegreen: {
r: 0.596078,
g: 0.984314,
b: 0.596078,
},
paleturquoise: {
r: 0.686275,
g: 0.933333,
b: 0.933333,
},
palevioletred: {
r: 0.858824,
g: 0.439216,
b: 0.576471,
},
papayawhip: {
r: 1,
g: 0.937255,
b: 0.835294,
},
peachpuff: {
r: 1,
g: 0.854902,
b: 0.72549,
},
peru: {
r: 0.803922,
g: 0.521569,
b: 0.247059,
},
pink: {
r: 1,
g: 0.752941,
b: 0.796078,
},
plum: {
r: 0.866667,
g: 0.627451,
b: 0.866667,
},
powderblue: {
r: 0.690196,
g: 0.878431,
b: 0.901961,
},
purple: {
r: 0.501961,
g: 0,
b: 0.501961,
},
red: {
r: 1,
g: 0,
b: 0,
},
rosybrown: {
r: 0.737255,
g: 0.560784,
b: 0.560784,
},
royalblue: {
r: 0.254902,
g: 0.411765,
b: 0.882353,
},
saddlebrown: {
r: 0.545098,
g: 0.270588,
b: 0.07451,
},
salmon: {
r: 0.980392,
g: 0.501961,
b: 0.447059,
},
sandybrown: {
r: 0.956863,
g: 0.643137,
b: 0.376471,
},
seagreen: {
r: 0.180392,
g: 0.545098,
b: 0.341176,
},
seashell: {
r: 1,
g: 0.960784,
b: 0.933333,
},
sienna: {
r: 0.627451,
g: 0.321569,
b: 0.176471,
},
silver: {
r: 0.752941,
g: 0.752941,
b: 0.752941,
},
skyblue: {
r: 0.529412,
g: 0.807843,
b: 0.921569,
},
slateblue: {
r: 0.415686,
g: 0.352941,
b: 0.803922,
},
slategray: {
r: 0.439216,
g: 0.501961,
b: 0.564706,
},
slategrey: {
r: 0.439216,
g: 0.501961,
b: 0.564706,
},
snow: {
r: 1,
g: 0.980392,
b: 0.980392,
},
springgreen: {
r: 0,
g: 1,
b: 0.498039,
},
steelblue: {
r: 0.27451,
g: 0.509804,
b: 0.705882,
},
tan: {
r: 0.823529,
g: 0.705882,
b: 0.54902,
},
teal: {
r: 0,
g: 0.501961,
b: 0.501961,
},
thistle: {
r: 0.847059,
g: 0.74902,
b: 0.847059,
},
tomato: {
r: 1,
g: 0.388235,
b: 0.278431,
},
transparent: {
r: 0,
g: 0,
b: 0,
a: 0,
},
turquoise: {
r: 0.25098,
g: 0.878431,
b: 0.815686,
},
violet: {
r: 0.933333,
g: 0.509804,
b: 0.933333,
},
wheat: {
r: 0.960784,
g: 0.870588,
b: 0.701961,
},
white: {
r: 1,
g: 1,
b: 1,
},
whitesmoke: {
r: 0.960784,
g: 0.960784,
b: 0.960784,
},
yellow: {
r: 1,
g: 1,
b: 0,
},
yellowgreen: {
r: 0.603922,
g: 0.803922,
b: 0.196078,
},
};
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/parse-color.js
// Matches rgb(R, G, B) where R, G, and B are integers [0 - 255]
const webRGBRegex = /^rgb\(\s*((?:(?:25[0-5]|2[0-4]\d|1\d\d|\d{1,2})\s*,\s*){2}(?:25[0-5]|2[0-4]\d|1\d\d|\d{1,2})\s*)\)$/i;
// Matches rgb(R, G, B, A) where R, G, and B are integers [0 - 255] and A is [0-1] floating
const webRGBARegex = /^rgba\(\s*((?:(?:25[0-5]|2[0-4]\d|1\d\d|\d{1,2})\s*,\s*){3}(?:0|1|0?\.\d*)\s*)\)$/i;
// Matches #RGB and #RRGGBB, where R, G, and B are [0-9] or [A-F]
const hexRGBRegex = /^#((?:[0-9a-f]{6}|[0-9a-f]{3}))$/i;
// Matches #RGB and #RRGGBBAA, where R, G, B, and A are [0-9] or [A-F]
const hexRGBARegex = /^#((?:[0-9a-f]{8}|[0-9a-f]{4}))$/i;
/**
* Test if a color matches #RRGGBB or #RGB
* @public
*/
function isColorStringHexRGB(raw) {
return hexRGBRegex.test(raw);
}
/**
* Test if a color matches #AARRGGBB or #ARGB
* @public
*/
function isColorStringHexARGB(raw) {
return hexRGBARegex.test(raw);
}
/**
* Test if a color matches #RRGGBBAA or #RGBA
* @public
*/
function isColorStringHexRGBA(raw) {
return isColorStringHexARGB(raw); // No way to differentiate these two formats, so just use the same test
}
/**
* Test if a color matches rgb(rr, gg, bb)
* @public
*/
function isColorStringWebRGB(raw) {
return webRGBRegex.test(raw);
}
/**
* Test if a color matches rgba(rr, gg, bb, aa)
*
* @public
*/
function isColorStringWebRGBA(raw) {
return webRGBARegex.test(raw);
}
/**
* Tests whether a color is in {@link @microsoft/fast-colors#NamedColors}.
* @param raw - the color name to test
* @public
*/
function isColorNamed(raw) {
return namedColorsConfigs.hasOwnProperty(raw);
}
/**
* Converts a hexadecimal color string to a {@link @microsoft/fast-colors#ColorRGBA64}.
* @param raw - a color string in the form of "#RRGGBB" or "#RGB"
* @example
* ```ts
* parseColorHexRGBA("#FF0000");
* parseColorHexRGBA("#F00");
* ```
* @public
*/
function parseColorHexRGB(raw) {
const result = hexRGBRegex.exec(raw);
if (result === null) {
return null;
}
let digits = result[1];
if (digits.length === 3) {
const r = digits.charAt(0);
const g = digits.charAt(1);
const b = digits.charAt(2);
digits = r.concat(r, g, g, b, b);
}
const rawInt = parseInt(digits, 16);
if (isNaN(rawInt)) {
return null;
}
// Note the use of >>> rather than >> as we want JS to manipulate these as unsigned numbers
return new color_rgba_64_ColorRGBA64(math_utilities_normalize((rawInt & 0xff0000) >>> 16, 0, 255), math_utilities_normalize((rawInt & 0x00ff00) >>> 8, 0, 255), math_utilities_normalize(rawInt & 0x0000ff, 0, 255), 1);
}
/**
* Converts a hexadecimal color string to a {@link @microsoft/fast-colors#ColorRGBA64}.
* @param raw - a color string in the form of "#AARRGGBB" or "#ARGB"
* @example
* ```ts
* parseColorHexRGBA("#AAFF0000");
* parseColorHexRGBA("#AF00");
* ```
* @public
*/
function parseColorHexARGB(raw) {
const result = hexRGBARegex.exec(raw);
if (result === null) {
return null;
}
let digits = result[1];
if (digits.length === 4) {
const a = digits.charAt(0);
const r = digits.charAt(1);
const g = digits.charAt(2);
const b = digits.charAt(3);
digits = a.concat(a, r, r, g, g, b, b);
}
const rawInt = parseInt(digits, 16);
if (isNaN(rawInt)) {
return null;
}
// Note the use of >>> rather than >> as we want JS to manipulate these as unsigned numbers
return new color_rgba_64_ColorRGBA64(math_utilities_normalize((rawInt & 0x00ff0000) >>> 16, 0, 255), math_utilities_normalize((rawInt & 0x0000ff00) >>> 8, 0, 255), math_utilities_normalize(rawInt & 0x000000ff, 0, 255), math_utilities_normalize((rawInt & 0xff000000) >>> 24, 0, 255));
}
/**
* Converts a hexadecimal color string to a {@link @microsoft/fast-colors#ColorRGBA64}.
* @param raw - a color string in the form of "#RRGGBBAA" or "#RGBA"
* @example
* ```ts
* parseColorHexRGBA("#FF0000AA");
* parseColorHexRGBA("#F00A");
* ```
* @public
*/
function parseColorHexRGBA(raw) {
const result = hexRGBARegex.exec(raw);
if (result === null) {
return null;
}
let digits = result[1];
if (digits.length === 4) {
const r = digits.charAt(0);
const g = digits.charAt(1);
const b = digits.charAt(2);
const a = digits.charAt(3);
digits = r.concat(r, g, g, b, b, a, a);
}
const rawInt = parseInt(digits, 16);
if (isNaN(rawInt)) {
return null;
}
// Note the use of >>> rather than >> as we want JS to manipulate these as unsigned numbers
return new ColorRGBA64(normalize((rawInt & 0xff000000) >>> 24, 0, 255), normalize((rawInt & 0x00ff0000) >>> 16, 0, 255), normalize((rawInt & 0x0000ff00) >>> 8, 0, 255), normalize(rawInt & 0x000000ff, 0, 255));
}
/**
* Converts a rgb color string to a {@link @microsoft/fast-colors#ColorRGBA64}.
* @param raw - a color string format "rgba(RR,GG,BB)" where RR,GG,BB are [0,255]
* @example
* ```ts
* parseColorWebRGB("rgba(255, 0, 0");
* ```
* @public
*/
function parseColorWebRGB(raw) {
const result = webRGBRegex.exec(raw);
if (result === null) {
return null;
}
const split = result[1].split(",");
return new color_rgba_64_ColorRGBA64(math_utilities_normalize(Number(split[0]), 0, 255), math_utilities_normalize(Number(split[1]), 0, 255), math_utilities_normalize(Number(split[2]), 0, 255), 1);
}
/**
* Converts a rgba color string to a {@link @microsoft/fast-colors#ColorRGBA64}.
* @param raw - a color string format "rgba(RR,GG,BB,a)" where RR,GG,BB are [0,255] and a is [0,1]
* @example
* ```ts
* parseColorWebRGBA("rgba(255, 0, 0, 1");
* ```
* @public
*/
function parseColorWebRGBA(raw) {
const result = webRGBARegex.exec(raw);
if (result === null) {
return null;
}
const split = result[1].split(",");
if (split.length === 4) {
return new color_rgba_64_ColorRGBA64(math_utilities_normalize(Number(split[0]), 0, 255), math_utilities_normalize(Number(split[1]), 0, 255), math_utilities_normalize(Number(split[2]), 0, 255), Number(split[3]));
}
return null;
}
/**
* Converts a named color to a {@link @microsoft/fast-colors#ColorRGBA64}.
* @param raw - a {@link https://www.w3schools.com/colors/colors_names.asp | CSS color name}.
* @example
* ```ts
* parseColorNamed("red");
* ```
* @public
*/
function parseColorNamed(raw) {
// const rawLower: typeof raw = raw.toLowerCase() : raw.toString();
const config = namedColorsConfigs[raw.toLowerCase()];
return config
? new color_rgba_64_ColorRGBA64(config.r, config.g, config.b, config.hasOwnProperty("a") ? config.a : void 0)
: null;
}
/**
*
Expects any of the following and attempts to determine which is being used
* #RRGGBB, #AARRGGBB, rgb(RR,GG,BB) rgba(RR,GG,BB,a),
* or any of the {@link https://www.w3schools.com/colors/colors_names.asp | CSS color names}.
* @param raw - the color string to parse
* @public
*/
function parseColor(raw) {
const rawLower = raw.toLowerCase();
return isColorStringHexRGB(rawLower)
? parseColorHexRGB(rawLower)
: isColorStringHexRGBA(rawLower)
? parseColorHexARGB(rawLower)
: isColorStringWebRGB(rawLower)
? parseColorWebRGB(rawLower)
: isColorStringWebRGBA(rawLower)
? parseColorWebRGBA(rawLower)
: isColorNamed(rawLower)
? parseColorNamed(rawLower)
: null;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-hsl.js
/**
* This uses Hue values in "degree" format. So expect a range of [0,360]. Some other implementations instead uses radians or a normalized Hue with range [0,1]. Be aware of this when checking values or using other libraries.
*
* @public
*/
class color_hsl_ColorHSL {
constructor(hue, sat, lum) {
this.h = hue;
this.s = sat;
this.l = lum;
}
/**
* Construct a {@link ColorHSL} from a config object.
*/
static fromObject(data) {
if (data && !isNaN(data.h) && !isNaN(data.s) && !isNaN(data.l)) {
return new color_hsl_ColorHSL(data.h, data.s, data.l);
}
return null;
}
/**
* Determines if a color is equal to another
* @param rhs - the value to compare
*/
equalValue(rhs) {
return this.h === rhs.h && this.s === rhs.s && this.l === rhs.l;
}
/**
* Returns a new {@link ColorHSL} rounded to the provided precision
* @param precision - the precision to round to
*/
roundToPrecision(precision) {
return new color_hsl_ColorHSL(roundToPrecisionSmall(this.h, precision), roundToPrecisionSmall(this.s, precision), roundToPrecisionSmall(this.l, precision));
}
/**
* Returns the {@link ColorHSL} formatted as an object.
*/
toObject() {
return { h: this.h, s: this.s, l: this.l };
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-hsv.js
/**
* This uses Hue values in "degree" format. So expect a range of [0,360]. Some other implementations instead uses radians or a normalized Hue with range [0,1]. Be aware of this when checking values or using other libraries.
*
* @public
*/
class ColorHSV {
constructor(hue, sat, val) {
this.h = hue;
this.s = sat;
this.v = val;
}
/**
* Construct a {@link ColorHSV} from a config object.
*/
static fromObject(data) {
if (data && !isNaN(data.h) && !isNaN(data.s) && !isNaN(data.v)) {
return new ColorHSV(data.h, data.s, data.v);
}
return null;
}
/**
* Determines if a color is equal to another
* @param rhs - the value to compare
*/
equalValue(rhs) {
return this.h === rhs.h && this.s === rhs.s && this.v === rhs.v;
}
/**
* Returns a new {@link ColorHSV} rounded to the provided precision
* @param precision - the precision to round to
*/
roundToPrecision(precision) {
return new ColorHSV(roundToPrecisionSmall(this.h, precision), roundToPrecisionSmall(this.s, precision), roundToPrecisionSmall(this.v, precision));
}
/**
* Returns the {@link ColorHSV} formatted as an object.
*/
toObject() {
return { h: this.h, s: this.s, v: this.v };
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-lab.js
/**
* {@link https://en.wikipedia.org/wiki/CIELAB_color_space | CIELAB color space}
* This implementation uses the D65 constants for 2 degrees. That determines the constants used for the pure white point of the XYZ space of 0.95047, 1.0, 1.08883.
* {@link https://en.wikipedia.org/wiki/Illuminant_D65}
* These constants determine how the XYZ, LCH and LAB colors convert to/from RGB.
*
* @public
*/
class color_lab_ColorLAB {
constructor(l, a, b) {
this.l = l;
this.a = a;
this.b = b;
}
/**
* Construct a {@link ColorLAB} from a config object.
*/
static fromObject(data) {
if (data && !isNaN(data.l) && !isNaN(data.a) && !isNaN(data.b)) {
return new color_lab_ColorLAB(data.l, data.a, data.b);
}
return null;
}
/**
* Determines if a color is equal to another
* @param rhs - the value to compare
*/
equalValue(rhs) {
return this.l === rhs.l && this.a === rhs.a && this.b === rhs.b;
}
/**
* Returns a new {@link ColorLAB} rounded to the provided precision
* @param precision - the precision to round to
*/
roundToPrecision(precision) {
return new color_lab_ColorLAB(roundToPrecisionSmall(this.l, precision), roundToPrecisionSmall(this.a, precision), roundToPrecisionSmall(this.b, precision));
}
/**
* Returns the {@link ColorLAB} formatted as an object.
*/
toObject() {
return { l: this.l, a: this.a, b: this.b };
}
}
color_lab_ColorLAB.epsilon = 216 / 24389;
color_lab_ColorLAB.kappa = 24389 / 27;
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-lch.js
/**
*
* {@link https://en.wikipedia.org/wiki/CIELAB_color_space | CIELCH color space}
*
* This is a cylindrical representation of the CIELAB space useful for saturation operations
* This uses Hue values in "degree" format. So expect a range of [0,360]. Some other implementations instead uses radians or a normalized Hue with range [0,1]. Be aware of this when checking values or using other libraries.
* This implementation uses the D65 constants for 2 degrees. That determines the constants used for the pure white point of the XYZ space of 0.95047, 1.0, 1.08883.
* {@link https://en.wikipedia.org/wiki/Illuminant_D65}
* These constants determine how the XYZ, LCH and LAB colors convert to/from RGB.
*
* @public
*/
class ColorLCH {
constructor(l, c, h) {
this.l = l;
this.c = c;
this.h = h;
}
/**
* Construct a {@link ColorLCH} from a config object.
* @param data - the config object
*/
static fromObject(data) {
if (data && !isNaN(data.l) && !isNaN(data.c) && !isNaN(data.h)) {
return new ColorLCH(data.l, data.c, data.h);
}
return null;
}
/**
* Determines if one color is equal to another.
* @param rhs - the color to compare
*/
equalValue(rhs) {
return this.l === rhs.l && this.c === rhs.c && this.h === rhs.h;
}
/**
* Returns a new {@link ColorLCH} rounded to the provided precision
* @param precision - the precision to round to
*/
roundToPrecision(precision) {
return new ColorLCH(roundToPrecisionSmall(this.l, precision), roundToPrecisionSmall(this.c, precision), roundToPrecisionSmall(this.h, precision));
}
/**
* Converts the {@link ColorLCH} to a config object.
*/
toObject() {
return { l: this.l, c: this.c, h: this.h };
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-xyz.js
/**
* {@link https://en.wikipedia.org/wiki/CIE_1931_color_space | XYZ color space}
*
* This implementation uses the D65 constants for 2 degrees. That determines the constants used for the pure white point of the XYZ space of 0.95047, 1.0, 1.08883.
* {@link https://en.wikipedia.org/wiki/Illuminant_D65}
* These constants determine how the XYZ, LCH and LAB colors convert to/from RGB.
*
* @public
*/
class ColorXYZ {
constructor(x, y, z) {
this.x = x;
this.y = y;
this.z = z;
}
/**
* Construct a {@link ColorXYZ} from a config object.
*/
static fromObject(data) {
if (data && !isNaN(data.x) && !isNaN(data.y) && !isNaN(data.z)) {
return new ColorXYZ(data.x, data.y, data.z);
}
return null;
}
/**
* Determines if a color is equal to another
* @param rhs - the value to compare
*/
equalValue(rhs) {
return this.x === rhs.x && this.y === rhs.y && this.z === rhs.z;
}
/**
* Returns a new {@link ColorXYZ} rounded to the provided precision
* @param precision - the precision to round to
*/
roundToPrecision(precision) {
return new ColorXYZ(roundToPrecisionSmall(this.x, precision), roundToPrecisionSmall(this.y, precision), roundToPrecisionSmall(this.z, precision));
}
/**
* Returns the {@link ColorXYZ} formatted as an object.
*/
toObject() {
return { x: this.x, y: this.y, z: this.z };
}
}
/**
* D65 2 degree white point
*/
ColorXYZ.whitePoint = new ColorXYZ(0.95047, 1.0, 1.08883);
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-converters.js
// All hue values are in degrees rather than radians or normalized
// All conversions use the D65 2 degree white point for XYZ
// Info on conversions and constants used can be found in the following:
// https://en.wikipedia.org/wiki/CIELAB_color_space
// https://en.wikipedia.org/wiki/Illuminant_D65
// https://ninedegreesbelow.com/photography/xyz-rgb.html
// http://user.engineering.uiowa.edu/~aip/Misc/ColorFAQ.html
// https://web.stanford.edu/~sujason/ColorBalancing/adaptation.html
// http://brucelindbloom.com/index.html
/**
* Get the luminance of a color in the linear RGB space.
* This is not the same as the relative luminance in the sRGB space for WCAG contrast calculations. Use rgbToRelativeLuminance instead.
* @param rgb - The input color
*
* @public
*/
function rgbToLinearLuminance(rgb) {
return rgb.r * 0.2126 + rgb.g * 0.7152 + rgb.b * 0.0722;
}
/**
* Get the relative luminance of a color.
* Adjusts the color to sRGB space, which is necessary for the WCAG contrast spec.
* The alpha channel of the input is ignored.
* @param rgb - The input color
*
* @public
*/
function rgbToRelativeLuminance(rgb) {
function luminanceHelper(i) {
if (i <= 0.03928) {
return i / 12.92;
}
return Math.pow((i + 0.055) / 1.055, 2.4);
}
return rgbToLinearLuminance(new color_rgba_64_ColorRGBA64(luminanceHelper(rgb.r), luminanceHelper(rgb.g), luminanceHelper(rgb.b), 1));
}
const calculateContrastRatio = (a, b) => (a + 0.05) / (b + 0.05);
/**
* Calculate the contrast ratio between two colors. Uses the formula described by {@link https://www.w3.org/TR/WCAG20-TECHS/G17.html | WCAG 2.0}.
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function contrastRatio(a, b) {
const luminanceA = rgbToRelativeLuminance(a);
const luminanceB = rgbToRelativeLuminance(b);
return luminanceA > luminanceB
? calculateContrastRatio(luminanceA, luminanceB)
: calculateContrastRatio(luminanceB, luminanceA);
}
function calcChannelOverlay(match, background, overlay) {
if (overlay - background === 0) {
return 0;
}
else {
return (match - background) / (overlay - background);
}
}
function calcRgbOverlay(rgbMatch, rgbBackground, rgbOverlay) {
const rChannel = calcChannelOverlay(rgbMatch.r, rgbBackground.r, rgbOverlay.r);
const gChannel = calcChannelOverlay(rgbMatch.g, rgbBackground.g, rgbOverlay.g);
const bChannel = calcChannelOverlay(rgbMatch.b, rgbBackground.b, rgbOverlay.b);
return (rChannel + gChannel + bChannel) / 3;
}
/**
* Calculate an overlay color that uses rgba (rgb + alpha) that matches the appearance of a given solid color when placed on the same background
* @param rgbMatch - The solid color the overlay should match in appearance when placed over the rgbBackground
* @param rgbBackground - The background on which the overlay rests
* @param rgbOverlay - The rgb color of the overlay. Typically this is either pure white or pure black and when not provided will be determined automatically. This color will be used in the returned output
* @returns The rgba (rgb + alpha) color of the overlay
*
* @public
*/
function calculateOverlayColor(rgbMatch, rgbBackground, rgbOverlay = null) {
let alpha = 0;
let overlay = rgbOverlay;
if (overlay !== null) {
alpha = calcRgbOverlay(rgbMatch, rgbBackground, overlay);
}
else {
overlay = new ColorRGBA64(0, 0, 0, 1);
alpha = calcRgbOverlay(rgbMatch, rgbBackground, overlay);
if (alpha <= 0) {
overlay = new ColorRGBA64(1, 1, 1, 1);
alpha = calcRgbOverlay(rgbMatch, rgbBackground, overlay);
}
}
alpha = Math.round(alpha * 1000) / 1000;
return new ColorRGBA64(overlay.r, overlay.g, overlay.b, alpha);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorRGBA64} to a {@link @microsoft/fast-colors#ColorHSL}
* @param rgb - the rgb color to convert
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function color_converters_rgbToHSL(rgb) {
const max = Math.max(rgb.r, rgb.g, rgb.b);
const min = Math.min(rgb.r, rgb.g, rgb.b);
const delta = max - min;
let hue = 0;
if (delta !== 0) {
if (max === rgb.r) {
hue = 60 * (((rgb.g - rgb.b) / delta) % 6);
}
else if (max === rgb.g) {
hue = 60 * ((rgb.b - rgb.r) / delta + 2);
}
else {
hue = 60 * ((rgb.r - rgb.g) / delta + 4);
}
}
if (hue < 0) {
hue += 360;
}
const lum = (max + min) / 2;
let sat = 0;
if (delta !== 0) {
sat = delta / (1 - Math.abs(2 * lum - 1));
}
return new color_hsl_ColorHSL(hue, sat, lum);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorHSL} to a {@link @microsoft/fast-colors#ColorRGBA64}
* @param hsl - the hsl color to convert
* @param alpha - the alpha value
*
* @public
*/
function color_converters_hslToRGB(hsl, alpha = 1) {
const c = (1 - Math.abs(2 * hsl.l - 1)) * hsl.s;
const x = c * (1 - Math.abs(((hsl.h / 60) % 2) - 1));
const m = hsl.l - c / 2;
let r = 0;
let g = 0;
let b = 0;
if (hsl.h < 60) {
r = c;
g = x;
b = 0;
}
else if (hsl.h < 120) {
r = x;
g = c;
b = 0;
}
else if (hsl.h < 180) {
r = 0;
g = c;
b = x;
}
else if (hsl.h < 240) {
r = 0;
g = x;
b = c;
}
else if (hsl.h < 300) {
r = x;
g = 0;
b = c;
}
else if (hsl.h < 360) {
r = c;
g = 0;
b = x;
}
return new color_rgba_64_ColorRGBA64(r + m, g + m, b + m, alpha);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorRGBA64} to a {@link @microsoft/fast-colors#ColorHSV}
* @param rgb - the rgb color to convert
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function rgbToHSV(rgb) {
const max = Math.max(rgb.r, rgb.g, rgb.b);
const min = Math.min(rgb.r, rgb.g, rgb.b);
const delta = max - min;
let hue = 0;
if (delta !== 0) {
if (max === rgb.r) {
hue = 60 * (((rgb.g - rgb.b) / delta) % 6);
}
else if (max === rgb.g) {
hue = 60 * ((rgb.b - rgb.r) / delta + 2);
}
else {
hue = 60 * ((rgb.r - rgb.g) / delta + 4);
}
}
if (hue < 0) {
hue += 360;
}
let sat = 0;
if (max !== 0) {
sat = delta / max;
}
return new ColorHSV(hue, sat, max);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorHSV} to a {@link @microsoft/fast-colors#ColorRGBA64}
* @param hsv - the hsv color to convert
* @param alpha - the alpha value
*
* @public
*/
function hsvToRGB(hsv, alpha = 1) {
const c = hsv.s * hsv.v;
const x = c * (1 - Math.abs(((hsv.h / 60) % 2) - 1));
const m = hsv.v - c;
let r = 0;
let g = 0;
let b = 0;
if (hsv.h < 60) {
r = c;
g = x;
b = 0;
}
else if (hsv.h < 120) {
r = x;
g = c;
b = 0;
}
else if (hsv.h < 180) {
r = 0;
g = c;
b = x;
}
else if (hsv.h < 240) {
r = 0;
g = x;
b = c;
}
else if (hsv.h < 300) {
r = x;
g = 0;
b = c;
}
else if (hsv.h < 360) {
r = c;
g = 0;
b = x;
}
return new color_rgba_64_ColorRGBA64(r + m, g + m, b + m, alpha);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorLCH} to a {@link @microsoft/fast-colors#ColorLAB}
* @param lch - the lch color to convert
*
* @public
*/
function lchToLAB(lch) {
let a = 0;
let b = 0;
if (lch.h !== 0) {
a = Math.cos(degreesToRadians(lch.h)) * lch.c;
b = Math.sin(degreesToRadians(lch.h)) * lch.c;
}
return new color_lab_ColorLAB(lch.l, a, b);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorLAB} to a {@link @microsoft/fast-colors#ColorLCH}
* @param lab - the lab color to convert
*
* @remarks
* The discontinuity in the C parameter at 0 means that floating point errors will often result in values near 0 giving unpredictable results.
* EG: 0.0000001 gives a very different result than -0.0000001
* In cases where both a and b are very near zero this function will return an LCH color with an H of 0
* More info about the atan2 function: {@link https://en.wikipedia.org/wiki/Atan2}
* @public
*/
function labToLCH(lab) {
let h = 0;
// Because of the discontinuity at 0 if a number is very close to 0 - often due to floating point errors - then
// it gives unexpected results. EG: 0.000000000001 gives a different result than 0. So just avoid any number
// that has both a and b very close to zero and lump it in with the h = 0 case.
if (Math.abs(lab.b) > 0.001 || Math.abs(lab.a) > 0.001) {
h = radiansToDegrees(Math.atan2(lab.b, lab.a));
}
if (h < 0) {
h += 360;
}
const c = Math.sqrt(lab.a * lab.a + lab.b * lab.b);
return new ColorLCH(lab.l, c, h);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorLAB} to a {@link @microsoft/fast-colors#ColorXYZ}
* @param lab - the lab color to convert
*
* @public
*/
function labToXYZ(lab) {
const fy = (lab.l + 16) / 116;
const fx = fy + lab.a / 500;
const fz = fy - lab.b / 200;
const xcubed = Math.pow(fx, 3);
const ycubed = Math.pow(fy, 3);
const zcubed = Math.pow(fz, 3);
let x = 0;
if (xcubed > color_lab_ColorLAB.epsilon) {
x = xcubed;
}
else {
x = (116 * fx - 16) / color_lab_ColorLAB.kappa;
}
let y = 0;
if (lab.l > color_lab_ColorLAB.epsilon * color_lab_ColorLAB.kappa) {
y = ycubed;
}
else {
y = lab.l / color_lab_ColorLAB.kappa;
}
let z = 0;
if (zcubed > color_lab_ColorLAB.epsilon) {
z = zcubed;
}
else {
z = (116 * fz - 16) / color_lab_ColorLAB.kappa;
}
x = ColorXYZ.whitePoint.x * x;
y = ColorXYZ.whitePoint.y * y;
z = ColorXYZ.whitePoint.z * z;
return new ColorXYZ(x, y, z);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorXYZ} to a {@link @microsoft/fast-colors#ColorLAB}
* @param xyz - the xyz color to convert
*
* @public
*/
function xyzToLAB(xyz) {
function xyzToLABHelper(i) {
if (i > color_lab_ColorLAB.epsilon) {
return Math.pow(i, 1 / 3);
}
return (color_lab_ColorLAB.kappa * i + 16) / 116;
}
const x = xyzToLABHelper(xyz.x / ColorXYZ.whitePoint.x);
const y = xyzToLABHelper(xyz.y / ColorXYZ.whitePoint.y);
const z = xyzToLABHelper(xyz.z / ColorXYZ.whitePoint.z);
const l = 116 * y - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return new color_lab_ColorLAB(l, a, b);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorRGBA64} to a {@link @microsoft/fast-colors#ColorXYZ}
* @param rgb - the rgb color to convert
*
* @remarks
* The alpha channel of the input is ignored
* @public
*/
function rgbToXYZ(rgb) {
function rgbToXYZHelper(i) {
if (i <= 0.04045) {
return i / 12.92;
}
return Math.pow((i + 0.055) / 1.055, 2.4);
}
const r = rgbToXYZHelper(rgb.r);
const g = rgbToXYZHelper(rgb.g);
const b = rgbToXYZHelper(rgb.b);
const x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375;
const y = r * 0.2126729 + g * 0.7151522 + b * 0.072175;
const z = r * 0.0193339 + g * 0.119192 + b * 0.9503041;
return new ColorXYZ(x, y, z);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorXYZ} to a {@link @microsoft/fast-colors#ColorRGBA64}
* @param xyz - the xyz color to convert
* @param alpha - the alpha value
*
* @remarks
* Note that the xyz color space is significantly larger than sRGB. As such, this can return colors rgb values greater than 1 or less than 0
* @public
*/
function xyzToRGB(xyz, alpha = 1) {
function xyzToRGBHelper(i) {
if (i <= 0.0031308) {
return i * 12.92;
}
return 1.055 * Math.pow(i, 1 / 2.4) - 0.055;
}
const r = xyzToRGBHelper(xyz.x * 3.2404542 - xyz.y * 1.5371385 - xyz.z * 0.4985314);
const g = xyzToRGBHelper(xyz.x * -0.969266 + xyz.y * 1.8760108 + xyz.z * 0.041556);
const b = xyzToRGBHelper(xyz.x * 0.0556434 - xyz.y * 0.2040259 + xyz.z * 1.0572252);
return new color_rgba_64_ColorRGBA64(r, g, b, alpha);
}
/**
* Converts a {@link @microsoft/fast-colors#ColorRGBA64} to a {@link @microsoft/fast-colors#ColorLAB}
* @param rgb - the rgb color to convert
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function color_converters_rgbToLAB(rgb) {
return xyzToLAB(rgbToXYZ(rgb));
}
/**
* Converts a {@link @microsoft/fast-colors#ColorLAB} to a {@link @microsoft/fast-colors#ColorRGBA64}
* @param lab - the LAB color to convert
* @param alpha - the alpha value
*
* @remarks
* Note that the xyz color space (which the conversion from LAB uses) is significantly larger than sRGB. As such, this can return colors rgb values greater than 1 or less than 0
*
* @public
*/
function color_converters_labToRGB(lab, alpha = 1) {
return xyzToRGB(labToXYZ(lab), alpha);
}
/**
* Convert a {@link @microsoft/fast-colors#ColorRGBA64} to a {@link @microsoft/fast-colors#ColorLCH}
*
* @param rgb - the rgb color to convert
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function rgbToLCH(rgb) {
return labToLCH(color_converters_rgbToLAB(rgb));
}
/**
* Convert a {@link @microsoft/fast-colors#ColorLCH} to a {@link @microsoft/fast-colors#ColorRGBA64}
* @param lch - the LCH color to convert
* @param alpha - the alpha value
*
* @public
*/
function lchToRGB(lch, alpha = 1) {
return color_converters_labToRGB(lchToLAB(lch), alpha);
}
/**
* Converts a color temperature to a {@link @microsoft/fast-colors#ColorRGBA64}
* @param tempKelvin - the temperature to convert
* @param alpha - the alpha value
*
* @public
*/
function temperatureToRGB(tempKelvin, alpha = 1) {
// The constants I could find assumed a decimal range of [0,255] for each channel. Just going to put a /255.0 at the end
let r = 0;
let g = 0;
let b = 0;
if (tempKelvin <= 1000) {
tempKelvin = 1000;
}
else if (tempKelvin >= 40000) {
tempKelvin = 40000;
}
if (tempKelvin < 6600.0) {
r = 255.0;
g = tempKelvin / 100.0 - 2.0;
g =
-155.25485562709179 -
0.44596950469579133 * g +
104.49216199393888 * Math.log(g);
}
else {
r = tempKelvin / 100.0 - 55.0;
r = 351.97690566805693 + 0.114206453784165 * r - 40.25366309332127 * Math.log(r);
g = tempKelvin / 100.0 - 50.0;
g = 325.4494125711974 + 0.07943456536662342 * g - 28.0852963507957 * Math.log(g);
}
if (tempKelvin >= 6600.0) {
b = 255.0;
}
else if (tempKelvin < 2000.0) {
b = 0.0;
}
else {
b = tempKelvin / 100.0 - 10;
b =
-254.76935184120902 +
0.8274096064007395 * b +
115.67994401066147 * Math.log(b);
}
return new ColorRGBA64(r / 255, g / 255, b / 255, alpha);
}
/**
* Convert a rgb color to a color temperature
* @param rgb - the color to convert
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function rgbToTemperature(rgb) {
let t = 0;
let min = 1000;
let max = 40000;
while (max - min > 0.4) {
t = (max + min) / 2.0;
const testColor = temperatureToRGB(t);
if (testColor.b / testColor.r >= rgb.b / rgb.r) {
max = t;
}
else {
min = t;
}
}
return Math.round(t);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/utilities/relative-luminance.js
/**
* @internal
*/
function contrast(a, b) {
const L1 = a.relativeLuminance > b.relativeLuminance ? a : b;
const L2 = a.relativeLuminance > b.relativeLuminance ? b : a;
return (L1.relativeLuminance + 0.05) / (L2.relativeLuminance + 0.05);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/swatch.js
/** @public */
const SwatchRGB = Object.freeze({
create(r, g, b) {
return new SwatchRGBImpl(r, g, b);
},
from(obj) {
return new SwatchRGBImpl(obj.r, obj.g, obj.b);
}
});
/**
* Runtime test for an objects conformance with the SwatchRGB interface.
* @internal
*/
function isSwatchRGB(value) {
const test = {
r: 0,
g: 0,
b: 0,
toColorString: () => '',
contrast: () => 0,
relativeLuminance: 0
};
for (const key in test) {
// @ts-expect-error swatch has no index
if (typeof test[key] !== typeof value[key]) {
return false;
}
}
return true;
}
/**
* A RGB implementation of {@link Swatch}
* @internal
*/
class SwatchRGBImpl extends color_rgba_64_ColorRGBA64 {
/**
*
* @param red - Red channel expressed as a number between 0 and 1
* @param green - Green channel expressed as a number between 0 and 1
* @param blue - Blue channel expressed as a number between 0 and 1
*/
constructor(red, green, blue) {
super(red, green, blue, 1);
this.toColorString = this.toStringHexRGB;
this.contrast = contrast.bind(null, this);
this.createCSS = this.toColorString;
this.relativeLuminance = rgbToRelativeLuminance(this);
}
static fromObject(obj) {
return new SwatchRGBImpl(obj.r, obj.g, obj.b);
}
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/utilities/base-layer-luminance.js
function baseLayerLuminanceSwatch(luminance) {
return SwatchRGB.create(luminance, luminance, luminance);
}
/**
* Recommended values for light and dark mode for {@link @microsoft/fast-components#baseLayerLuminance}.
*
* @public
*/
const StandardLuminance = {
LightMode: 1,
DarkMode: 0.23
};
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/utilities/is-dark.js
/*
* A color is in "dark" if there is more contrast between #000000 and a reference
* color than #FFFFFF and the reference color. That threshold can be expressed as a relative luminance
* using the contrast formula as (1 + 0.5) / (R + 0.05) === (R + 0.05) / (0 + 0.05),
* which reduces to the following, where 'R' is the relative luminance of the reference color
*/
const target = (-0.1 + Math.sqrt(0.21)) / 2;
/**
* Determines if a color should be considered Dark Mode
* @param color - The color to check to mode of
* @returns boolean
*
* @public
*/
function isDark(color) {
return color.relativeLuminance <= target;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/node_modules/tslib/tslib.es6.js
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
}
return __assign.apply(this, arguments);
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __createBinding(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}
function __exportStar(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
function __importStar(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/styles/css-directive.js
/**
* Directive for use in {@link css}.
*
* @public
*/
class CSSDirective {
/**
* Creates a CSS fragment to interpolate into the CSS document.
* @returns - the string to interpolate into CSS
*/
createCSS() {
return "";
}
/**
* Creates a behavior to bind to the host element.
* @returns - the behavior to bind to the host element, or undefined.
*/
createBehavior() {
return undefined;
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/platform.js
/**
* A reference to globalThis, with support
* for browsers that don't yet support the spec.
* @public
*/
const $global = (function () {
if (typeof globalThis !== "undefined") {
// We're running in a modern environment.
return globalThis;
}
if (typeof __webpack_require__.g !== "undefined") {
// We're running in NodeJS
return __webpack_require__.g;
}
if (typeof self !== "undefined") {
// We're running in a worker.
return self;
}
if (typeof window !== "undefined") {
// We're running in the browser's main thread.
return window;
}
try {
// Hopefully we never get here...
// Not all environments allow eval and Function. Use only as a last resort:
// eslint-disable-next-line no-new-func
return new Function("return this")();
}
catch (_a) {
// If all fails, give up and create an object.
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
return {};
}
})();
// API-only Polyfill for trustedTypes
if ($global.trustedTypes === void 0) {
$global.trustedTypes = { createPolicy: (n, r) => r };
}
const propConfig = {
configurable: false,
enumerable: false,
writable: false,
};
if ($global.FAST === void 0) {
Reflect.defineProperty($global, "FAST", Object.assign({ value: Object.create(null) }, propConfig));
}
/**
* The FAST global.
* @internal
*/
const FAST = $global.FAST;
if (FAST.getById === void 0) {
const storage = Object.create(null);
Reflect.defineProperty(FAST, "getById", Object.assign({ value(id, initialize) {
let found = storage[id];
if (found === void 0) {
found = initialize ? (storage[id] = initialize()) : null;
}
return found;
} }, propConfig));
}
/**
* A readonly, empty array.
* @remarks
* Typically returned by APIs that return arrays when there are
* no actual items to return.
* @internal
*/
const emptyArray = Object.freeze([]);
/**
* Creates a function capable of locating metadata associated with a type.
* @returns A metadata locator function.
* @internal
*/
function createMetadataLocator() {
const metadataLookup = new WeakMap();
return function (target) {
let metadata = metadataLookup.get(target);
if (metadata === void 0) {
let currentTarget = Reflect.getPrototypeOf(target);
while (metadata === void 0 && currentTarget !== null) {
metadata = metadataLookup.get(currentTarget);
currentTarget = Reflect.getPrototypeOf(currentTarget);
}
metadata = metadata === void 0 ? [] : metadata.slice(0);
metadataLookup.set(target, metadata);
}
return metadata;
};
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/dom.js
const updateQueue = $global.FAST.getById(1 /* updateQueue */, () => {
const tasks = [];
const pendingErrors = [];
function throwFirstError() {
if (pendingErrors.length) {
throw pendingErrors.shift();
}
}
function tryRunTask(task) {
try {
task.call();
}
catch (error) {
pendingErrors.push(error);
setTimeout(throwFirstError, 0);
}
}
function process() {
const capacity = 1024;
let index = 0;
while (index < tasks.length) {
tryRunTask(tasks[index]);
index++;
// Prevent leaking memory for long chains of recursive calls to `DOM.queueUpdate`.
// If we call `DOM.queueUpdate` within a task scheduled by `DOM.queueUpdate`, the queue will
// grow, but to avoid an O(n) walk for every task we execute, we don't
// shift tasks off the queue after they have been executed.
// Instead, we periodically shift 1024 tasks off the queue.
if (index > capacity) {
// Manually shift all values starting at the index back to the
// beginning of the queue.
for (let scan = 0, newLength = tasks.length - index; scan < newLength; scan++) {
tasks[scan] = tasks[scan + index];
}
tasks.length -= index;
index = 0;
}
}
tasks.length = 0;
}
function enqueue(callable) {
if (tasks.length < 1) {
$global.requestAnimationFrame(process);
}
tasks.push(callable);
}
return Object.freeze({
enqueue,
process,
});
});
/* eslint-disable */
const fastHTMLPolicy = $global.trustedTypes.createPolicy("fast-html", {
createHTML: html => html,
});
/* eslint-enable */
let htmlPolicy = fastHTMLPolicy;
const marker = `fast-${Math.random().toString(36).substring(2, 8)}`;
/** @internal */
const _interpolationStart = `${marker}{`;
/** @internal */
const _interpolationEnd = `}${marker}`;
/**
* Common DOM APIs.
* @public
*/
const DOM = Object.freeze({
/**
* Indicates whether the DOM supports the adoptedStyleSheets feature.
*/
supportsAdoptedStyleSheets: Array.isArray(document.adoptedStyleSheets) &&
"replace" in CSSStyleSheet.prototype,
/**
* Sets the HTML trusted types policy used by the templating engine.
* @param policy - The policy to set for HTML.
* @remarks
* This API can only be called once, for security reasons. It should be
* called by the application developer at the start of their program.
*/
setHTMLPolicy(policy) {
if (htmlPolicy !== fastHTMLPolicy) {
throw new Error("The HTML policy can only be set once.");
}
htmlPolicy = policy;
},
/**
* Turns a string into trusted HTML using the configured trusted types policy.
* @param html - The string to turn into trusted HTML.
* @remarks
* Used internally by the template engine when creating templates
* and setting innerHTML.
*/
createHTML(html) {
return htmlPolicy.createHTML(html);
},
/**
* Determines if the provided node is a template marker used by the runtime.
* @param node - The node to test.
*/
isMarker(node) {
return node && node.nodeType === 8 && node.data.startsWith(marker);
},
/**
* Given a marker node, extract the {@link HTMLDirective} index from the placeholder.
* @param node - The marker node to extract the index from.
*/
extractDirectiveIndexFromMarker(node) {
return parseInt(node.data.replace(`${marker}:`, ""));
},
/**
* Creates a placeholder string suitable for marking out a location *within*
* an attribute value or HTML content.
* @param index - The directive index to create the placeholder for.
* @remarks
* Used internally by binding directives.
*/
createInterpolationPlaceholder(index) {
return `${_interpolationStart}${index}${_interpolationEnd}`;
},
/**
* Creates a placeholder that manifests itself as an attribute on an
* element.
* @param attributeName - The name of the custom attribute.
* @param index - The directive index to create the placeholder for.
* @remarks
* Used internally by attribute directives such as `ref`, `slotted`, and `children`.
*/
createCustomAttributePlaceholder(attributeName, index) {
return `${attributeName}="${this.createInterpolationPlaceholder(index)}"`;
},
/**
* Creates a placeholder that manifests itself as a marker within the DOM structure.
* @param index - The directive index to create the placeholder for.
* @remarks
* Used internally by structural directives such as `repeat`.
*/
createBlockPlaceholder(index) {
return ``;
},
/**
* Schedules DOM update work in the next async batch.
* @param callable - The callable function or object to queue.
*/
queueUpdate: updateQueue.enqueue,
/**
* Immediately processes all work previously scheduled
* through queueUpdate.
* @remarks
* This also forces nextUpdate promises
* to resolve.
*/
processUpdates: updateQueue.process,
/**
* Resolves with the next DOM update.
*/
nextUpdate() {
return new Promise(updateQueue.enqueue);
},
/**
* Sets an attribute value on an element.
* @param element - The element to set the attribute value on.
* @param attributeName - The attribute name to set.
* @param value - The value of the attribute to set.
* @remarks
* If the value is `null` or `undefined`, the attribute is removed, otherwise
* it is set to the provided value using the standard `setAttribute` API.
*/
setAttribute(element, attributeName, value) {
if (value === null || value === undefined) {
element.removeAttribute(attributeName);
}
else {
element.setAttribute(attributeName, value);
}
},
/**
* Sets a boolean attribute value.
* @param element - The element to set the boolean attribute value on.
* @param attributeName - The attribute name to set.
* @param value - The value of the attribute to set.
* @remarks
* If the value is true, the attribute is added; otherwise it is removed.
*/
setBooleanAttribute(element, attributeName, value) {
value
? element.setAttribute(attributeName, "")
: element.removeAttribute(attributeName);
},
/**
* Removes all the child nodes of the provided parent node.
* @param parent - The node to remove the children from.
*/
removeChildNodes(parent) {
for (let child = parent.firstChild; child !== null; child = parent.firstChild) {
parent.removeChild(child);
}
},
/**
* Creates a TreeWalker configured to walk a template fragment.
* @param fragment - The fragment to walk.
*/
createTemplateWalker(fragment) {
return document.createTreeWalker(fragment, 133, // element, text, comment
null, false);
},
});
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/observation/notifier.js
/**
* An implementation of {@link Notifier} that efficiently keeps track of
* subscribers interested in a specific change notification on an
* observable source.
*
* @remarks
* This set is optimized for the most common scenario of 1 or 2 subscribers.
* With this in mind, it can store a subscriber in an internal field, allowing it to avoid Array#push operations.
* If the set ever exceeds two subscribers, it upgrades to an array automatically.
* @public
*/
class SubscriberSet {
/**
* Creates an instance of SubscriberSet for the specified source.
* @param source - The object source that subscribers will receive notifications from.
* @param initialSubscriber - An initial subscriber to changes.
*/
constructor(source, initialSubscriber) {
this.sub1 = void 0;
this.sub2 = void 0;
this.spillover = void 0;
this.source = source;
this.sub1 = initialSubscriber;
}
/**
* Checks whether the provided subscriber has been added to this set.
* @param subscriber - The subscriber to test for inclusion in this set.
*/
has(subscriber) {
return this.spillover === void 0
? this.sub1 === subscriber || this.sub2 === subscriber
: this.spillover.indexOf(subscriber) !== -1;
}
/**
* Subscribes to notification of changes in an object's state.
* @param subscriber - The object that is subscribing for change notification.
*/
subscribe(subscriber) {
const spillover = this.spillover;
if (spillover === void 0) {
if (this.has(subscriber)) {
return;
}
if (this.sub1 === void 0) {
this.sub1 = subscriber;
return;
}
if (this.sub2 === void 0) {
this.sub2 = subscriber;
return;
}
this.spillover = [this.sub1, this.sub2, subscriber];
this.sub1 = void 0;
this.sub2 = void 0;
}
else {
const index = spillover.indexOf(subscriber);
if (index === -1) {
spillover.push(subscriber);
}
}
}
/**
* Unsubscribes from notification of changes in an object's state.
* @param subscriber - The object that is unsubscribing from change notification.
*/
unsubscribe(subscriber) {
const spillover = this.spillover;
if (spillover === void 0) {
if (this.sub1 === subscriber) {
this.sub1 = void 0;
}
else if (this.sub2 === subscriber) {
this.sub2 = void 0;
}
}
else {
const index = spillover.indexOf(subscriber);
if (index !== -1) {
spillover.splice(index, 1);
}
}
}
/**
* Notifies all subscribers.
* @param args - Data passed along to subscribers during notification.
*/
notify(args) {
const spillover = this.spillover;
const source = this.source;
if (spillover === void 0) {
const sub1 = this.sub1;
const sub2 = this.sub2;
if (sub1 !== void 0) {
sub1.handleChange(source, args);
}
if (sub2 !== void 0) {
sub2.handleChange(source, args);
}
}
else {
for (let i = 0, ii = spillover.length; i < ii; ++i) {
spillover[i].handleChange(source, args);
}
}
}
}
/**
* An implementation of Notifier that allows subscribers to be notified
* of individual property changes on an object.
* @public
*/
class PropertyChangeNotifier {
/**
* Creates an instance of PropertyChangeNotifier for the specified source.
* @param source - The object source that subscribers will receive notifications from.
*/
constructor(source) {
this.subscribers = {};
this.sourceSubscribers = null;
this.source = source;
}
/**
* Notifies all subscribers, based on the specified property.
* @param propertyName - The property name, passed along to subscribers during notification.
*/
notify(propertyName) {
var _a;
const subscribers = this.subscribers[propertyName];
if (subscribers !== void 0) {
subscribers.notify(propertyName);
}
(_a = this.sourceSubscribers) === null || _a === void 0 ? void 0 : _a.notify(propertyName);
}
/**
* Subscribes to notification of changes in an object's state.
* @param subscriber - The object that is subscribing for change notification.
* @param propertyToWatch - The name of the property that the subscriber is interested in watching for changes.
*/
subscribe(subscriber, propertyToWatch) {
var _a;
if (propertyToWatch) {
let subscribers = this.subscribers[propertyToWatch];
if (subscribers === void 0) {
this.subscribers[propertyToWatch] = subscribers = new SubscriberSet(this.source);
}
subscribers.subscribe(subscriber);
}
else {
this.sourceSubscribers =
(_a = this.sourceSubscribers) !== null && _a !== void 0 ? _a : new SubscriberSet(this.source);
this.sourceSubscribers.subscribe(subscriber);
}
}
/**
* Unsubscribes from notification of changes in an object's state.
* @param subscriber - The object that is unsubscribing from change notification.
* @param propertyToUnwatch - The name of the property that the subscriber is no longer interested in watching.
*/
unsubscribe(subscriber, propertyToUnwatch) {
var _a;
if (propertyToUnwatch) {
const subscribers = this.subscribers[propertyToUnwatch];
if (subscribers !== void 0) {
subscribers.unsubscribe(subscriber);
}
}
else {
(_a = this.sourceSubscribers) === null || _a === void 0 ? void 0 : _a.unsubscribe(subscriber);
}
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/observation/observable.js
/**
* Common Observable APIs.
* @public
*/
const Observable = FAST.getById(2 /* observable */, () => {
const volatileRegex = /(:|&&|\|\||if)/;
const notifierLookup = new WeakMap();
const queueUpdate = DOM.queueUpdate;
let watcher = void 0;
let createArrayObserver = (array) => {
throw new Error("Must call enableArrayObservation before observing arrays.");
};
function getNotifier(source) {
let found = source.$fastController || notifierLookup.get(source);
if (found === void 0) {
if (Array.isArray(source)) {
found = createArrayObserver(source);
}
else {
notifierLookup.set(source, (found = new PropertyChangeNotifier(source)));
}
}
return found;
}
const getAccessors = createMetadataLocator();
class DefaultObservableAccessor {
constructor(name) {
this.name = name;
this.field = `_${name}`;
this.callback = `${name}Changed`;
}
getValue(source) {
if (watcher !== void 0) {
watcher.watch(source, this.name);
}
return source[this.field];
}
setValue(source, newValue) {
const field = this.field;
const oldValue = source[field];
if (oldValue !== newValue) {
source[field] = newValue;
const callback = source[this.callback];
if (typeof callback === "function") {
callback.call(source, oldValue, newValue);
}
getNotifier(source).notify(this.name);
}
}
}
class BindingObserverImplementation extends SubscriberSet {
constructor(binding, initialSubscriber, isVolatileBinding = false) {
super(binding, initialSubscriber);
this.binding = binding;
this.isVolatileBinding = isVolatileBinding;
this.needsRefresh = true;
this.needsQueue = true;
this.first = this;
this.last = null;
this.propertySource = void 0;
this.propertyName = void 0;
this.notifier = void 0;
this.next = void 0;
}
observe(source, context) {
if (this.needsRefresh && this.last !== null) {
this.disconnect();
}
const previousWatcher = watcher;
watcher = this.needsRefresh ? this : void 0;
this.needsRefresh = this.isVolatileBinding;
const result = this.binding(source, context);
watcher = previousWatcher;
return result;
}
disconnect() {
if (this.last !== null) {
let current = this.first;
while (current !== void 0) {
current.notifier.unsubscribe(this, current.propertyName);
current = current.next;
}
this.last = null;
this.needsRefresh = this.needsQueue = true;
}
}
watch(propertySource, propertyName) {
const prev = this.last;
const notifier = getNotifier(propertySource);
const current = prev === null ? this.first : {};
current.propertySource = propertySource;
current.propertyName = propertyName;
current.notifier = notifier;
notifier.subscribe(this, propertyName);
if (prev !== null) {
if (!this.needsRefresh) {
// Declaring the variable prior to assignment below circumvents
// a bug in Angular's optimization process causing infinite recursion
// of this watch() method. Details https://github.com/microsoft/fast/issues/4969
let prevValue;
watcher = void 0;
/* eslint-disable-next-line */
prevValue = prev.propertySource[prev.propertyName];
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
watcher = this;
if (propertySource === prevValue) {
this.needsRefresh = true;
}
}
prev.next = current;
}
this.last = current;
}
handleChange() {
if (this.needsQueue) {
this.needsQueue = false;
queueUpdate(this);
}
}
call() {
if (this.last !== null) {
this.needsQueue = true;
this.notify(this);
}
}
records() {
let next = this.first;
return {
next: () => {
const current = next;
if (current === undefined) {
return { value: void 0, done: true };
}
else {
next = next.next;
return {
value: current,
done: false,
};
}
},
[Symbol.iterator]: function () {
return this;
},
};
}
}
return Object.freeze({
/**
* @internal
* @param factory - The factory used to create array observers.
*/
setArrayObserverFactory(factory) {
createArrayObserver = factory;
},
/**
* Gets a notifier for an object or Array.
* @param source - The object or Array to get the notifier for.
*/
getNotifier,
/**
* Records a property change for a source object.
* @param source - The object to record the change against.
* @param propertyName - The property to track as changed.
*/
track(source, propertyName) {
if (watcher !== void 0) {
watcher.watch(source, propertyName);
}
},
/**
* Notifies watchers that the currently executing property getter or function is volatile
* with respect to its observable dependencies.
*/
trackVolatile() {
if (watcher !== void 0) {
watcher.needsRefresh = true;
}
},
/**
* Notifies subscribers of a source object of changes.
* @param source - the object to notify of changes.
* @param args - The change args to pass to subscribers.
*/
notify(source, args) {
getNotifier(source).notify(args);
},
/**
* Defines an observable property on an object or prototype.
* @param target - The target object to define the observable on.
* @param nameOrAccessor - The name of the property to define as observable;
* or a custom accessor that specifies the property name and accessor implementation.
*/
defineProperty(target, nameOrAccessor) {
if (typeof nameOrAccessor === "string") {
nameOrAccessor = new DefaultObservableAccessor(nameOrAccessor);
}
getAccessors(target).push(nameOrAccessor);
Reflect.defineProperty(target, nameOrAccessor.name, {
enumerable: true,
get: function () {
return nameOrAccessor.getValue(this);
},
set: function (newValue) {
nameOrAccessor.setValue(this, newValue);
},
});
},
/**
* Finds all the observable accessors defined on the target,
* including its prototype chain.
* @param target - The target object to search for accessor on.
*/
getAccessors,
/**
* Creates a {@link BindingObserver} that can watch the
* provided {@link Binding} for changes.
* @param binding - The binding to observe.
* @param initialSubscriber - An initial subscriber to changes in the binding value.
* @param isVolatileBinding - Indicates whether the binding's dependency list must be re-evaluated on every value evaluation.
*/
binding(binding, initialSubscriber, isVolatileBinding = this.isVolatileBinding(binding)) {
return new BindingObserverImplementation(binding, initialSubscriber, isVolatileBinding);
},
/**
* Determines whether a binding expression is volatile and needs to have its dependency list re-evaluated
* on every evaluation of the value.
* @param binding - The binding to inspect.
*/
isVolatileBinding(binding) {
return volatileRegex.test(binding.toString());
},
});
});
/**
* Decorator: Defines an observable property on the target.
* @param target - The target to define the observable on.
* @param nameOrAccessor - The property name or accessor to define the observable as.
* @public
*/
function observable(target, nameOrAccessor) {
Observable.defineProperty(target, nameOrAccessor);
}
/**
* Decorator: Marks a property getter as having volatile observable dependencies.
* @param target - The target that the property is defined on.
* @param name - The property name.
* @param name - The existing descriptor.
* @public
*/
function observable_volatile(target, name, descriptor) {
return Object.assign({}, descriptor, {
get: function () {
Observable.trackVolatile();
return descriptor.get.apply(this);
},
});
}
const contextEvent = FAST.getById(3 /* contextEvent */, () => {
let current = null;
return {
get() {
return current;
},
set(event) {
current = event;
},
};
});
/**
* Provides additional contextual information available to behaviors and expressions.
* @public
*/
class ExecutionContext {
constructor() {
/**
* The index of the current item within a repeat context.
*/
this.index = 0;
/**
* The length of the current collection within a repeat context.
*/
this.length = 0;
/**
* The parent data object within a repeat context.
*/
this.parent = null;
/**
* The parent execution context when in nested context scenarios.
*/
this.parentContext = null;
}
/**
* The current event within an event handler.
*/
get event() {
return contextEvent.get();
}
/**
* Indicates whether the current item within a repeat context
* has an even index.
*/
get isEven() {
return this.index % 2 === 0;
}
/**
* Indicates whether the current item within a repeat context
* has an odd index.
*/
get isOdd() {
return this.index % 2 !== 0;
}
/**
* Indicates whether the current item within a repeat context
* is the first item in the collection.
*/
get isFirst() {
return this.index === 0;
}
/**
* Indicates whether the current item within a repeat context
* is somewhere in the middle of the collection.
*/
get isInMiddle() {
return !this.isFirst && !this.isLast;
}
/**
* Indicates whether the current item within a repeat context
* is the last item in the collection.
*/
get isLast() {
return this.index === this.length - 1;
}
/**
* Sets the event for the current execution context.
* @param event - The event to set.
* @internal
*/
static setEvent(event) {
contextEvent.set(event);
}
}
Observable.defineProperty(ExecutionContext.prototype, "index");
Observable.defineProperty(ExecutionContext.prototype, "length");
/**
* The default execution context used in binding expressions.
* @public
*/
const defaultExecutionContext = Object.seal(new ExecutionContext());
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/styles/element-styles.js
/**
* Represents styles that can be applied to a custom element.
* @public
*/
class ElementStyles {
constructor() {
this.targets = new WeakSet();
}
/** @internal */
addStylesTo(target) {
this.targets.add(target);
}
/** @internal */
removeStylesFrom(target) {
this.targets.delete(target);
}
/** @internal */
isAttachedTo(target) {
return this.targets.has(target);
}
/**
* Associates behaviors with this set of styles.
* @param behaviors - The behaviors to associate.
*/
withBehaviors(...behaviors) {
this.behaviors =
this.behaviors === null ? behaviors : this.behaviors.concat(behaviors);
return this;
}
}
/**
* Create ElementStyles from ComposableStyles.
*/
ElementStyles.create = (() => {
if (DOM.supportsAdoptedStyleSheets) {
const styleSheetCache = new Map();
return (styles) =>
// eslint-disable-next-line @typescript-eslint/no-use-before-define
new AdoptedStyleSheetsStyles(styles, styleSheetCache);
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return (styles) => new StyleElementStyles(styles);
})();
function reduceStyles(styles) {
return styles
.map((x) => x instanceof ElementStyles ? reduceStyles(x.styles) : [x])
.reduce((prev, curr) => prev.concat(curr), []);
}
function reduceBehaviors(styles) {
return styles
.map((x) => (x instanceof ElementStyles ? x.behaviors : null))
.reduce((prev, curr) => {
if (curr === null) {
return prev;
}
if (prev === null) {
prev = [];
}
return prev.concat(curr);
}, null);
}
let addAdoptedStyleSheets = (target, sheets) => {
target.adoptedStyleSheets = [...target.adoptedStyleSheets, ...sheets];
};
let removeAdoptedStyleSheets = (target, sheets) => {
target.adoptedStyleSheets = target.adoptedStyleSheets.filter((x) => sheets.indexOf(x) === -1);
};
if (DOM.supportsAdoptedStyleSheets) {
try {
// Test if browser implementation uses FrozenArray.
// If not, use push / splice to alter the stylesheets
// in place. This circumvents a bug in Safari 16.4 where
// periodically, assigning the array would previously
// cause sheets to be removed.
document.adoptedStyleSheets.push();
document.adoptedStyleSheets.splice();
addAdoptedStyleSheets = (target, sheets) => {
target.adoptedStyleSheets.push(...sheets);
};
removeAdoptedStyleSheets = (target, sheets) => {
for (const sheet of sheets) {
const index = target.adoptedStyleSheets.indexOf(sheet);
if (index !== -1) {
target.adoptedStyleSheets.splice(index, 1);
}
}
};
}
catch (e) {
// Do nothing if an error is thrown, the default
// case handles FrozenArray.
}
}
/**
* https://wicg.github.io/construct-stylesheets/
* https://developers.google.com/web/updates/2019/02/constructable-stylesheets
*
* @internal
*/
class AdoptedStyleSheetsStyles extends ElementStyles {
constructor(styles, styleSheetCache) {
super();
this.styles = styles;
this.styleSheetCache = styleSheetCache;
this._styleSheets = void 0;
this.behaviors = reduceBehaviors(styles);
}
get styleSheets() {
if (this._styleSheets === void 0) {
const styles = this.styles;
const styleSheetCache = this.styleSheetCache;
this._styleSheets = reduceStyles(styles).map((x) => {
if (x instanceof CSSStyleSheet) {
return x;
}
let sheet = styleSheetCache.get(x);
if (sheet === void 0) {
sheet = new CSSStyleSheet();
sheet.replaceSync(x);
styleSheetCache.set(x, sheet);
}
return sheet;
});
}
return this._styleSheets;
}
addStylesTo(target) {
addAdoptedStyleSheets(target, this.styleSheets);
super.addStylesTo(target);
}
removeStylesFrom(target) {
removeAdoptedStyleSheets(target, this.styleSheets);
super.removeStylesFrom(target);
}
}
let styleClassId = 0;
function getNextStyleClass() {
return `fast-style-class-${++styleClassId}`;
}
/**
* @internal
*/
class StyleElementStyles extends ElementStyles {
constructor(styles) {
super();
this.styles = styles;
this.behaviors = null;
this.behaviors = reduceBehaviors(styles);
this.styleSheets = reduceStyles(styles);
this.styleClass = getNextStyleClass();
}
addStylesTo(target) {
const styleSheets = this.styleSheets;
const styleClass = this.styleClass;
target = this.normalizeTarget(target);
for (let i = 0; i < styleSheets.length; i++) {
const element = document.createElement("style");
element.innerHTML = styleSheets[i];
element.className = styleClass;
target.append(element);
}
super.addStylesTo(target);
}
removeStylesFrom(target) {
target = this.normalizeTarget(target);
const styles = target.querySelectorAll(`.${this.styleClass}`);
for (let i = 0, ii = styles.length; i < ii; ++i) {
target.removeChild(styles[i]);
}
super.removeStylesFrom(target);
}
isAttachedTo(target) {
return super.isAttachedTo(this.normalizeTarget(target));
}
normalizeTarget(target) {
return target === document ? document.body : target;
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/components/attributes.js
/**
* Metadata used to configure a custom attribute's behavior.
* @public
*/
const AttributeConfiguration = Object.freeze({
/**
* Locates all attribute configurations associated with a type.
*/
locate: createMetadataLocator(),
});
/**
* A {@link ValueConverter} that converts to and from `boolean` values.
* @remarks
* Used automatically when the `boolean` {@link AttributeMode} is selected.
* @public
*/
const booleanConverter = {
toView(value) {
return value ? "true" : "false";
},
fromView(value) {
if (value === null ||
value === void 0 ||
value === "false" ||
value === false ||
value === 0) {
return false;
}
return true;
},
};
/**
* A {@link ValueConverter} that converts to and from `number` values.
* @remarks
* This converter allows for nullable numbers, returning `null` if the
* input was `null`, `undefined`, or `NaN`.
* @public
*/
const nullableNumberConverter = {
toView(value) {
if (value === null || value === undefined) {
return null;
}
const number = value * 1;
return isNaN(number) ? null : number.toString();
},
fromView(value) {
if (value === null || value === undefined) {
return null;
}
const number = value * 1;
return isNaN(number) ? null : number;
},
};
/**
* An implementation of {@link Accessor} that supports reactivity,
* change callbacks, attribute reflection, and type conversion for
* custom elements.
* @public
*/
class AttributeDefinition {
/**
* Creates an instance of AttributeDefinition.
* @param Owner - The class constructor that owns this attribute.
* @param name - The name of the property associated with the attribute.
* @param attribute - The name of the attribute in HTML.
* @param mode - The {@link AttributeMode} that describes the behavior of this attribute.
* @param converter - A {@link ValueConverter} that integrates with the property getter/setter
* to convert values to and from a DOM string.
*/
constructor(Owner, name, attribute = name.toLowerCase(), mode = "reflect", converter) {
this.guards = new Set();
this.Owner = Owner;
this.name = name;
this.attribute = attribute;
this.mode = mode;
this.converter = converter;
this.fieldName = `_${name}`;
this.callbackName = `${name}Changed`;
this.hasCallback = this.callbackName in Owner.prototype;
if (mode === "boolean" && converter === void 0) {
this.converter = booleanConverter;
}
}
/**
* Sets the value of the attribute/property on the source element.
* @param source - The source element to access.
* @param value - The value to set the attribute/property to.
*/
setValue(source, newValue) {
const oldValue = source[this.fieldName];
const converter = this.converter;
if (converter !== void 0) {
newValue = converter.fromView(newValue);
}
if (oldValue !== newValue) {
source[this.fieldName] = newValue;
this.tryReflectToAttribute(source);
if (this.hasCallback) {
source[this.callbackName](oldValue, newValue);
}
source.$fastController.notify(this.name);
}
}
/**
* Gets the value of the attribute/property on the source element.
* @param source - The source element to access.
*/
getValue(source) {
Observable.track(source, this.name);
return source[this.fieldName];
}
/** @internal */
onAttributeChangedCallback(element, value) {
if (this.guards.has(element)) {
return;
}
this.guards.add(element);
this.setValue(element, value);
this.guards.delete(element);
}
tryReflectToAttribute(element) {
const mode = this.mode;
const guards = this.guards;
if (guards.has(element) || mode === "fromView") {
return;
}
DOM.queueUpdate(() => {
guards.add(element);
const latestValue = element[this.fieldName];
switch (mode) {
case "reflect":
const converter = this.converter;
DOM.setAttribute(element, this.attribute, converter !== void 0 ? converter.toView(latestValue) : latestValue);
break;
case "boolean":
DOM.setBooleanAttribute(element, this.attribute, latestValue);
break;
}
guards.delete(element);
});
}
/**
* Collects all attribute definitions associated with the owner.
* @param Owner - The class constructor to collect attribute for.
* @param attributeLists - Any existing attributes to collect and merge with those associated with the owner.
* @internal
*/
static collect(Owner, ...attributeLists) {
const attributes = [];
attributeLists.push(AttributeConfiguration.locate(Owner));
for (let i = 0, ii = attributeLists.length; i < ii; ++i) {
const list = attributeLists[i];
if (list === void 0) {
continue;
}
for (let j = 0, jj = list.length; j < jj; ++j) {
const config = list[j];
if (typeof config === "string") {
attributes.push(new AttributeDefinition(Owner, config));
}
else {
attributes.push(new AttributeDefinition(Owner, config.property, config.attribute, config.mode, config.converter));
}
}
}
return attributes;
}
}
function attr(configOrTarget, prop) {
let config;
function decorator($target, $prop) {
if (arguments.length > 1) {
// Non invocation:
// - @attr
// Invocation with or w/o opts:
// - @attr()
// - @attr({...opts})
config.property = $prop;
}
AttributeConfiguration.locate($target.constructor).push(config);
}
if (arguments.length > 1) {
// Non invocation:
// - @attr
config = {};
decorator(configOrTarget, prop);
return;
}
// Invocation with or w/o opts:
// - @attr()
// - @attr({...opts})
config = configOrTarget === void 0 ? {} : configOrTarget;
return decorator;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/components/fast-definitions.js
const defaultShadowOptions = { mode: "open" };
const defaultElementOptions = {};
const fastRegistry = FAST.getById(4 /* elementRegistry */, () => {
const typeToDefinition = new Map();
return Object.freeze({
register(definition) {
if (typeToDefinition.has(definition.type)) {
return false;
}
typeToDefinition.set(definition.type, definition);
return true;
},
getByType(key) {
return typeToDefinition.get(key);
},
});
});
/**
* Defines metadata for a FASTElement.
* @public
*/
class fast_definitions_FASTElementDefinition {
/**
* Creates an instance of FASTElementDefinition.
* @param type - The type this definition is being created for.
* @param nameOrConfig - The name of the element to define or a config object
* that describes the element to define.
*/
constructor(type, nameOrConfig = type.definition) {
if (typeof nameOrConfig === "string") {
nameOrConfig = { name: nameOrConfig };
}
this.type = type;
this.name = nameOrConfig.name;
this.template = nameOrConfig.template;
const attributes = AttributeDefinition.collect(type, nameOrConfig.attributes);
const observedAttributes = new Array(attributes.length);
const propertyLookup = {};
const attributeLookup = {};
for (let i = 0, ii = attributes.length; i < ii; ++i) {
const current = attributes[i];
observedAttributes[i] = current.attribute;
propertyLookup[current.name] = current;
attributeLookup[current.attribute] = current;
}
this.attributes = attributes;
this.observedAttributes = observedAttributes;
this.propertyLookup = propertyLookup;
this.attributeLookup = attributeLookup;
this.shadowOptions =
nameOrConfig.shadowOptions === void 0
? defaultShadowOptions
: nameOrConfig.shadowOptions === null
? void 0
: Object.assign(Object.assign({}, defaultShadowOptions), nameOrConfig.shadowOptions);
this.elementOptions =
nameOrConfig.elementOptions === void 0
? defaultElementOptions
: Object.assign(Object.assign({}, defaultElementOptions), nameOrConfig.elementOptions);
this.styles =
nameOrConfig.styles === void 0
? void 0
: Array.isArray(nameOrConfig.styles)
? ElementStyles.create(nameOrConfig.styles)
: nameOrConfig.styles instanceof ElementStyles
? nameOrConfig.styles
: ElementStyles.create([nameOrConfig.styles]);
}
/**
* Indicates if this element has been defined in at least one registry.
*/
get isDefined() {
return !!fastRegistry.getByType(this.type);
}
/**
* Defines a custom element based on this definition.
* @param registry - The element registry to define the element in.
*/
define(registry = customElements) {
const type = this.type;
if (fastRegistry.register(this)) {
const attributes = this.attributes;
const proto = type.prototype;
for (let i = 0, ii = attributes.length; i < ii; ++i) {
Observable.defineProperty(proto, attributes[i]);
}
Reflect.defineProperty(type, "observedAttributes", {
value: this.observedAttributes,
enumerable: true,
});
}
if (!registry.get(this.name)) {
registry.define(this.name, type, this.elementOptions);
}
return this;
}
}
/**
* Gets the element definition associated with the specified type.
* @param type - The custom element type to retrieve the definition for.
*/
fast_definitions_FASTElementDefinition.forType = fastRegistry.getByType;
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/components/controller.js
const shadowRoots = new WeakMap();
const defaultEventOptions = {
bubbles: true,
composed: true,
cancelable: true,
};
function getShadowRoot(element) {
return element.shadowRoot || shadowRoots.get(element) || null;
}
/**
* Controls the lifecycle and rendering of a `FASTElement`.
* @public
*/
class Controller extends PropertyChangeNotifier {
/**
* Creates a Controller to control the specified element.
* @param element - The element to be controlled by this controller.
* @param definition - The element definition metadata that instructs this
* controller in how to handle rendering and other platform integrations.
* @internal
*/
constructor(element, definition) {
super(element);
this.boundObservables = null;
this.behaviors = null;
this.needsInitialization = true;
this._template = null;
this._styles = null;
this._isConnected = false;
/**
* This allows Observable.getNotifier(...) to return the Controller
* when the notifier for the Controller itself is being requested. The
* result is that the Observable system does not need to create a separate
* instance of Notifier for observables on the Controller. The component and
* the controller will now share the same notifier, removing one-object construct
* per web component instance.
*/
this.$fastController = this;
/**
* The view associated with the custom element.
* @remarks
* If `null` then the element is managing its own rendering.
*/
this.view = null;
this.element = element;
this.definition = definition;
const shadowOptions = definition.shadowOptions;
if (shadowOptions !== void 0) {
const shadowRoot = element.attachShadow(shadowOptions);
if (shadowOptions.mode === "closed") {
shadowRoots.set(element, shadowRoot);
}
}
// Capture any observable values that were set by the binding engine before
// the browser upgraded the element. Then delete the property since it will
// shadow the getter/setter that is required to make the observable operate.
// Later, in the connect callback, we'll re-apply the values.
const accessors = Observable.getAccessors(element);
if (accessors.length > 0) {
const boundObservables = (this.boundObservables = Object.create(null));
for (let i = 0, ii = accessors.length; i < ii; ++i) {
const propertyName = accessors[i].name;
const value = element[propertyName];
if (value !== void 0) {
delete element[propertyName];
boundObservables[propertyName] = value;
}
}
}
}
/**
* Indicates whether or not the custom element has been
* connected to the document.
*/
get isConnected() {
Observable.track(this, "isConnected");
return this._isConnected;
}
setIsConnected(value) {
this._isConnected = value;
Observable.notify(this, "isConnected");
}
/**
* Gets/sets the template used to render the component.
* @remarks
* This value can only be accurately read after connect but can be set at any time.
*/
get template() {
return this._template;
}
set template(value) {
if (this._template === value) {
return;
}
this._template = value;
if (!this.needsInitialization) {
this.renderTemplate(value);
}
}
/**
* Gets/sets the primary styles used for the component.
* @remarks
* This value can only be accurately read after connect but can be set at any time.
*/
get styles() {
return this._styles;
}
set styles(value) {
if (this._styles === value) {
return;
}
if (this._styles !== null) {
this.removeStyles(this._styles);
}
this._styles = value;
if (!this.needsInitialization && value !== null) {
this.addStyles(value);
}
}
/**
* Adds styles to this element. Providing an HTMLStyleElement will attach the element instance to the shadowRoot.
* @param styles - The styles to add.
*/
addStyles(styles) {
const target = getShadowRoot(this.element) ||
this.element.getRootNode();
if (styles instanceof HTMLStyleElement) {
target.append(styles);
}
else if (!styles.isAttachedTo(target)) {
const sourceBehaviors = styles.behaviors;
styles.addStylesTo(target);
if (sourceBehaviors !== null) {
this.addBehaviors(sourceBehaviors);
}
}
}
/**
* Removes styles from this element. Providing an HTMLStyleElement will detach the element instance from the shadowRoot.
* @param styles - the styles to remove.
*/
removeStyles(styles) {
const target = getShadowRoot(this.element) ||
this.element.getRootNode();
if (styles instanceof HTMLStyleElement) {
target.removeChild(styles);
}
else if (styles.isAttachedTo(target)) {
const sourceBehaviors = styles.behaviors;
styles.removeStylesFrom(target);
if (sourceBehaviors !== null) {
this.removeBehaviors(sourceBehaviors);
}
}
}
/**
* Adds behaviors to this element.
* @param behaviors - The behaviors to add.
*/
addBehaviors(behaviors) {
const targetBehaviors = this.behaviors || (this.behaviors = new Map());
const length = behaviors.length;
const behaviorsToBind = [];
for (let i = 0; i < length; ++i) {
const behavior = behaviors[i];
if (targetBehaviors.has(behavior)) {
targetBehaviors.set(behavior, targetBehaviors.get(behavior) + 1);
}
else {
targetBehaviors.set(behavior, 1);
behaviorsToBind.push(behavior);
}
}
if (this._isConnected) {
const element = this.element;
for (let i = 0; i < behaviorsToBind.length; ++i) {
behaviorsToBind[i].bind(element, defaultExecutionContext);
}
}
}
/**
* Removes behaviors from this element.
* @param behaviors - The behaviors to remove.
* @param force - Forces unbinding of behaviors.
*/
removeBehaviors(behaviors, force = false) {
const targetBehaviors = this.behaviors;
if (targetBehaviors === null) {
return;
}
const length = behaviors.length;
const behaviorsToUnbind = [];
for (let i = 0; i < length; ++i) {
const behavior = behaviors[i];
if (targetBehaviors.has(behavior)) {
const count = targetBehaviors.get(behavior) - 1;
count === 0 || force
? targetBehaviors.delete(behavior) && behaviorsToUnbind.push(behavior)
: targetBehaviors.set(behavior, count);
}
}
if (this._isConnected) {
const element = this.element;
for (let i = 0; i < behaviorsToUnbind.length; ++i) {
behaviorsToUnbind[i].unbind(element);
}
}
}
/**
* Runs connected lifecycle behavior on the associated element.
*/
onConnectedCallback() {
if (this._isConnected) {
return;
}
const element = this.element;
if (this.needsInitialization) {
this.finishInitialization();
}
else if (this.view !== null) {
this.view.bind(element, defaultExecutionContext);
}
const behaviors = this.behaviors;
if (behaviors !== null) {
for (const [behavior] of behaviors) {
behavior.bind(element, defaultExecutionContext);
}
}
this.setIsConnected(true);
}
/**
* Runs disconnected lifecycle behavior on the associated element.
*/
onDisconnectedCallback() {
if (!this._isConnected) {
return;
}
this.setIsConnected(false);
const view = this.view;
if (view !== null) {
view.unbind();
}
const behaviors = this.behaviors;
if (behaviors !== null) {
const element = this.element;
for (const [behavior] of behaviors) {
behavior.unbind(element);
}
}
}
/**
* Runs the attribute changed callback for the associated element.
* @param name - The name of the attribute that changed.
* @param oldValue - The previous value of the attribute.
* @param newValue - The new value of the attribute.
*/
onAttributeChangedCallback(name, oldValue, newValue) {
const attrDef = this.definition.attributeLookup[name];
if (attrDef !== void 0) {
attrDef.onAttributeChangedCallback(this.element, newValue);
}
}
/**
* Emits a custom HTML event.
* @param type - The type name of the event.
* @param detail - The event detail object to send with the event.
* @param options - The event options. By default bubbles and composed.
* @remarks
* Only emits events if connected.
*/
emit(type, detail, options) {
if (this._isConnected) {
return this.element.dispatchEvent(new CustomEvent(type, Object.assign(Object.assign({ detail }, defaultEventOptions), options)));
}
return false;
}
finishInitialization() {
const element = this.element;
const boundObservables = this.boundObservables;
// If we have any observables that were bound, re-apply their values.
if (boundObservables !== null) {
const propertyNames = Object.keys(boundObservables);
for (let i = 0, ii = propertyNames.length; i < ii; ++i) {
const propertyName = propertyNames[i];
element[propertyName] = boundObservables[propertyName];
}
this.boundObservables = null;
}
const definition = this.definition;
// 1. Template overrides take top precedence.
if (this._template === null) {
if (this.element.resolveTemplate) {
// 2. Allow for element instance overrides next.
this._template = this.element.resolveTemplate();
}
else if (definition.template) {
// 3. Default to the static definition.
this._template = definition.template || null;
}
}
// If we have a template after the above process, render it.
// If there's no template, then the element author has opted into
// custom rendering and they will managed the shadow root's content themselves.
if (this._template !== null) {
this.renderTemplate(this._template);
}
// 1. Styles overrides take top precedence.
if (this._styles === null) {
if (this.element.resolveStyles) {
// 2. Allow for element instance overrides next.
this._styles = this.element.resolveStyles();
}
else if (definition.styles) {
// 3. Default to the static definition.
this._styles = definition.styles || null;
}
}
// If we have styles after the above process, add them.
if (this._styles !== null) {
this.addStyles(this._styles);
}
this.needsInitialization = false;
}
renderTemplate(template) {
const element = this.element;
// When getting the host to render to, we start by looking
// up the shadow root. If there isn't one, then that means
// we're doing a Light DOM render to the element's direct children.
const host = getShadowRoot(element) || element;
if (this.view !== null) {
// If there's already a view, we need to unbind and remove through dispose.
this.view.dispose();
this.view = null;
}
else if (!this.needsInitialization) {
// If there was previous custom rendering, we need to clear out the host.
DOM.removeChildNodes(host);
}
if (template) {
// If a new template was provided, render it.
this.view = template.render(element, host, element);
}
}
/**
* Locates or creates a controller for the specified element.
* @param element - The element to return the controller for.
* @remarks
* The specified element must have a {@link FASTElementDefinition}
* registered either through the use of the {@link customElement}
* decorator or a call to `FASTElement.define`.
*/
static forCustomElement(element) {
const controller = element.$fastController;
if (controller !== void 0) {
return controller;
}
const definition = fast_definitions_FASTElementDefinition.forType(element.constructor);
if (definition === void 0) {
throw new Error("Missing FASTElement definition.");
}
return (element.$fastController = new Controller(element, definition));
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/components/fast-element.js
/* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
function createFASTElement(BaseType) {
return class extends BaseType {
constructor() {
/* eslint-disable-next-line */
super();
Controller.forCustomElement(this);
}
$emit(type, detail, options) {
return this.$fastController.emit(type, detail, options);
}
connectedCallback() {
this.$fastController.onConnectedCallback();
}
disconnectedCallback() {
this.$fastController.onDisconnectedCallback();
}
attributeChangedCallback(name, oldValue, newValue) {
this.$fastController.onAttributeChangedCallback(name, oldValue, newValue);
}
};
}
/**
* A minimal base class for FASTElements that also provides
* static helpers for working with FASTElements.
* @public
*/
const FASTElement = Object.assign(createFASTElement(HTMLElement), {
/**
* Creates a new FASTElement base class inherited from the
* provided base type.
* @param BaseType - The base element type to inherit from.
*/
from(BaseType) {
return createFASTElement(BaseType);
},
/**
* Defines a platform custom element based on the provided type and definition.
* @param type - The custom element type to define.
* @param nameOrDef - The name of the element to define or a definition object
* that describes the element to define.
*/
define(type, nameOrDef) {
return new fast_definitions_FASTElementDefinition(type, nameOrDef).define().type;
},
});
/**
* Decorator: Defines a platform custom element based on `FASTElement`.
* @param nameOrDef - The name of the element to define or a definition object
* that describes the element to define.
* @public
*/
function customElement(nameOrDef) {
/* eslint-disable-next-line @typescript-eslint/explicit-function-return-type */
return function (type) {
new FASTElementDefinition(type, nameOrDef).define();
};
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/utilities/composed-parent.js
/**
* Retrieves the "composed parent" element of a node, ignoring DOM tree boundaries.
* When the parent of a node is a shadow-root, it will return the host
* element of the shadow root. Otherwise it will return the parent node or null if
* no parent node exists.
* @param element - The element for which to retrieve the composed parent
*
* @public
*/
function composedParent(element) {
const parentNode = element.parentElement;
if (parentNode) {
return parentNode;
}
else {
const rootNode = element.getRootNode();
if (rootNode.host instanceof HTMLElement) {
// this is shadow-root
return rootNode.host;
}
}
return null;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/utilities/composed-contains.js
/**
* Determines if the reference element contains the test element in a "composed" DOM tree that
* ignores shadow DOM boundaries.
*
* Returns true of the test element is a descendent of the reference, or exist in
* a shadow DOM that is a logical descendent of the reference. Otherwise returns false.
* @param reference - The element to test for containment against.
* @param test - The element being tested for containment.
*
* @public
*/
function composedContains(reference, test) {
let current = test;
while (current !== null) {
if (current === reference) {
return true;
}
current = composedParent(current);
}
return false;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/design-token/custom-property-manager.js
const defaultElement = document.createElement("div");
function isFastElement(element) {
return element instanceof FASTElement;
}
class QueuedStyleSheetTarget {
setProperty(name, value) {
DOM.queueUpdate(() => this.target.setProperty(name, value));
}
removeProperty(name) {
DOM.queueUpdate(() => this.target.removeProperty(name));
}
}
/**
* Handles setting properties for a FASTElement using Constructable Stylesheets
*/
class ConstructableStyleSheetTarget extends QueuedStyleSheetTarget {
constructor(source) {
super();
const sheet = new CSSStyleSheet();
this.target = sheet.cssRules[sheet.insertRule(":host{}")].style;
source.$fastController.addStyles(ElementStyles.create([sheet]));
}
}
class DocumentStyleSheetTarget extends QueuedStyleSheetTarget {
constructor() {
super();
const sheet = new CSSStyleSheet();
this.target = sheet.cssRules[sheet.insertRule(":root{}")].style;
document.adoptedStyleSheets = [
...document.adoptedStyleSheets,
sheet,
];
}
}
class HeadStyleElementStyleSheetTarget extends QueuedStyleSheetTarget {
constructor() {
super();
this.style = document.createElement("style");
document.head.appendChild(this.style);
const { sheet } = this.style;
// Because the HTMLStyleElement has been appended,
// there shouldn't exist a case where `sheet` is null,
// but if-check it just in case.
if (sheet) {
// https://github.com/jsdom/jsdom uses https://github.com/NV/CSSOM for it's CSSOM implementation,
// which implements the DOM Level 2 spec for CSSStyleSheet where insertRule() requires an index argument.
const index = sheet.insertRule(":root{}", sheet.cssRules.length);
this.target = sheet.cssRules[index].style;
}
}
}
/**
* Handles setting properties for a FASTElement using an HTMLStyleElement
*/
class StyleElementStyleSheetTarget {
constructor(target) {
this.store = new Map();
this.target = null;
const controller = target.$fastController;
this.style = document.createElement("style");
controller.addStyles(this.style);
Observable.getNotifier(controller).subscribe(this, "isConnected");
this.handleChange(controller, "isConnected");
}
targetChanged() {
if (this.target !== null) {
for (const [key, value] of this.store.entries()) {
this.target.setProperty(key, value);
}
}
}
setProperty(name, value) {
this.store.set(name, value);
DOM.queueUpdate(() => {
if (this.target !== null) {
this.target.setProperty(name, value);
}
});
}
removeProperty(name) {
this.store.delete(name);
DOM.queueUpdate(() => {
if (this.target !== null) {
this.target.removeProperty(name);
}
});
}
handleChange(source, key) {
// HTMLStyleElement.sheet is null if the element isn't connected to the DOM,
// so this method reacts to changes in DOM connection for the element hosting
// the HTMLStyleElement.
//
// All rules applied via the CSSOM also get cleared when the element disconnects,
// so we need to add a new rule each time and populate it with the stored properties
const { sheet } = this.style;
if (sheet) {
// Safari will throw if we try to use the return result of insertRule()
// to index the rule inline, so store as a const prior to indexing.
// https://github.com/jsdom/jsdom uses https://github.com/NV/CSSOM for it's CSSOM implementation,
// which implements the DOM Level 2 spec for CSSStyleSheet where insertRule() requires an index argument.
const index = sheet.insertRule(":host{}", sheet.cssRules.length);
this.target = sheet.cssRules[index].style;
}
else {
this.target = null;
}
}
}
__decorate([
observable
], StyleElementStyleSheetTarget.prototype, "target", void 0);
/**
* Handles setting properties for a normal HTMLElement
*/
class ElementStyleSheetTarget {
constructor(source) {
this.target = source.style;
}
setProperty(name, value) {
DOM.queueUpdate(() => this.target.setProperty(name, value));
}
removeProperty(name) {
DOM.queueUpdate(() => this.target.removeProperty(name));
}
}
/**
* Controls emission for default values. This control is capable
* of emitting to multiple {@link PropertyTarget | PropertyTargets},
* and only emits if it has at least one root.
*
* @internal
*/
class RootStyleSheetTarget {
setProperty(name, value) {
RootStyleSheetTarget.properties[name] = value;
for (const target of RootStyleSheetTarget.roots.values()) {
PropertyTargetManager.getOrCreate(RootStyleSheetTarget.normalizeRoot(target)).setProperty(name, value);
}
}
removeProperty(name) {
delete RootStyleSheetTarget.properties[name];
for (const target of RootStyleSheetTarget.roots.values()) {
PropertyTargetManager.getOrCreate(RootStyleSheetTarget.normalizeRoot(target)).removeProperty(name);
}
}
static registerRoot(root) {
const { roots } = RootStyleSheetTarget;
if (!roots.has(root)) {
roots.add(root);
const target = PropertyTargetManager.getOrCreate(this.normalizeRoot(root));
for (const key in RootStyleSheetTarget.properties) {
target.setProperty(key, RootStyleSheetTarget.properties[key]);
}
}
}
static unregisterRoot(root) {
const { roots } = RootStyleSheetTarget;
if (roots.has(root)) {
roots.delete(root);
const target = PropertyTargetManager.getOrCreate(RootStyleSheetTarget.normalizeRoot(root));
for (const key in RootStyleSheetTarget.properties) {
target.removeProperty(key);
}
}
}
/**
* Returns the document when provided the default element,
* otherwise is a no-op
* @param root - the root to normalize
*/
static normalizeRoot(root) {
return root === defaultElement ? document : root;
}
}
RootStyleSheetTarget.roots = new Set();
RootStyleSheetTarget.properties = {};
// Caches PropertyTarget instances
const propertyTargetCache = new WeakMap();
// Use Constructable StyleSheets for FAST elements when supported, otherwise use
// HTMLStyleElement instances
const propertyTargetCtor = DOM.supportsAdoptedStyleSheets
? ConstructableStyleSheetTarget
: StyleElementStyleSheetTarget;
/**
* Manages creation and caching of PropertyTarget instances.
*
* @internal
*/
const PropertyTargetManager = Object.freeze({
getOrCreate(source) {
if (propertyTargetCache.has(source)) {
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
return propertyTargetCache.get(source);
}
let target;
if (source === defaultElement) {
target = new RootStyleSheetTarget();
}
else if (source instanceof Document) {
target = DOM.supportsAdoptedStyleSheets
? new DocumentStyleSheetTarget()
: new HeadStyleElementStyleSheetTarget();
}
else if (isFastElement(source)) {
target = new propertyTargetCtor(source);
}
else {
target = new ElementStyleSheetTarget(source);
}
propertyTargetCache.set(source, target);
return target;
},
});
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/design-token/design-token.js
/**
* Implementation of {@link (DesignToken:interface)}
*/
class DesignTokenImpl extends CSSDirective {
constructor(configuration) {
super();
this.subscribers = new WeakMap();
this._appliedTo = new Set();
this.name = configuration.name;
if (configuration.cssCustomPropertyName !== null) {
this.cssCustomProperty = `--${configuration.cssCustomPropertyName}`;
this.cssVar = `var(${this.cssCustomProperty})`;
}
this.id = DesignTokenImpl.uniqueId();
DesignTokenImpl.tokensById.set(this.id, this);
}
get appliedTo() {
return [...this._appliedTo];
}
static from(nameOrConfig) {
return new DesignTokenImpl({
name: typeof nameOrConfig === "string" ? nameOrConfig : nameOrConfig.name,
cssCustomPropertyName: typeof nameOrConfig === "string"
? nameOrConfig
: nameOrConfig.cssCustomPropertyName === void 0
? nameOrConfig.name
: nameOrConfig.cssCustomPropertyName,
});
}
static isCSSDesignToken(token) {
return typeof token.cssCustomProperty === "string";
}
static isDerivedDesignTokenValue(value) {
return typeof value === "function";
}
/**
* Gets a token by ID. Returns undefined if the token was not found.
* @param id - The ID of the token
* @returns
*/
static getTokenById(id) {
return DesignTokenImpl.tokensById.get(id);
}
getOrCreateSubscriberSet(target = this) {
return (this.subscribers.get(target) ||
(this.subscribers.set(target, new Set()) && this.subscribers.get(target)));
}
createCSS() {
return this.cssVar || "";
}
getValueFor(element) {
const value = DesignTokenNode.getOrCreate(element).get(this);
if (value !== undefined) {
return value;
}
throw new Error(`Value could not be retrieved for token named "${this.name}". Ensure the value is set for ${element} or an ancestor of ${element}.`);
}
setValueFor(element, value) {
this._appliedTo.add(element);
if (value instanceof DesignTokenImpl) {
value = this.alias(value);
}
DesignTokenNode.getOrCreate(element).set(this, value);
return this;
}
deleteValueFor(element) {
this._appliedTo.delete(element);
if (DesignTokenNode.existsFor(element)) {
DesignTokenNode.getOrCreate(element).delete(this);
}
return this;
}
withDefault(value) {
this.setValueFor(defaultElement, value);
return this;
}
subscribe(subscriber, target) {
const subscriberSet = this.getOrCreateSubscriberSet(target);
if (target && !DesignTokenNode.existsFor(target)) {
DesignTokenNode.getOrCreate(target);
}
if (!subscriberSet.has(subscriber)) {
subscriberSet.add(subscriber);
}
}
unsubscribe(subscriber, target) {
const list = this.subscribers.get(target || this);
if (list && list.has(subscriber)) {
list.delete(subscriber);
}
}
/**
* Notifies subscribers that the value for an element has changed.
* @param element - The element to emit a notification for
*/
notify(element) {
const record = Object.freeze({ token: this, target: element });
if (this.subscribers.has(this)) {
this.subscribers.get(this).forEach(sub => sub.handleChange(record));
}
if (this.subscribers.has(element)) {
this.subscribers.get(element).forEach(sub => sub.handleChange(record));
}
}
/**
* Alias the token to the provided token.
* @param token - the token to alias to
*/
alias(token) {
return ((target) => token.getValueFor(target));
}
}
DesignTokenImpl.uniqueId = (() => {
let id = 0;
return () => {
id++;
return id.toString(16);
};
})();
/**
* Token storage by token ID
*/
DesignTokenImpl.tokensById = new Map();
class CustomPropertyReflector {
startReflection(token, target) {
token.subscribe(this, target);
this.handleChange({ token, target });
}
stopReflection(token, target) {
token.unsubscribe(this, target);
this.remove(token, target);
}
handleChange(record) {
const { token, target } = record;
this.add(token, target);
}
add(token, target) {
PropertyTargetManager.getOrCreate(target).setProperty(token.cssCustomProperty, this.resolveCSSValue(DesignTokenNode.getOrCreate(target).get(token)));
}
remove(token, target) {
PropertyTargetManager.getOrCreate(target).removeProperty(token.cssCustomProperty);
}
resolveCSSValue(value) {
return value && typeof value.createCSS === "function" ? value.createCSS() : value;
}
}
/**
* A light wrapper around BindingObserver to handle value caching and
* token notification
*/
class DesignTokenBindingObserver {
constructor(source, token, node) {
this.source = source;
this.token = token;
this.node = node;
this.dependencies = new Set();
this.observer = Observable.binding(source, this, false);
// This is a little bit hacky because it's using internal APIs of BindingObserverImpl.
// BindingObserverImpl queues updates to batch it's notifications which doesn't work for this
// scenario because the DesignToken.getValueFor API is not async. Without this, using DesignToken.getValueFor()
// after DesignToken.setValueFor() when setting a dependency of the value being retrieved can return a stale
// value. Assigning .handleChange to .call forces immediate invocation of this classes handleChange() method,
// allowing resolution of values synchronously.
// TODO: https://github.com/microsoft/fast/issues/5110
this.observer.handleChange = this.observer.call;
this.handleChange();
}
disconnect() {
this.observer.disconnect();
}
/**
* @internal
*/
handleChange() {
this.node.store.set(this.token, this.observer.observe(this.node.target, defaultExecutionContext));
}
}
/**
* Stores resolved token/value pairs and notifies on changes
*/
class Store {
constructor() {
this.values = new Map();
}
set(token, value) {
if (this.values.get(token) !== value) {
this.values.set(token, value);
Observable.getNotifier(this).notify(token.id);
}
}
get(token) {
Observable.track(this, token.id);
return this.values.get(token);
}
delete(token) {
this.values.delete(token);
}
all() {
return this.values.entries();
}
}
const nodeCache = new WeakMap();
const childToParent = new WeakMap();
/**
* A node responsible for setting and getting token values,
* emitting values to CSS custom properties, and maintaining
* inheritance structures.
*/
class DesignTokenNode {
constructor(target) {
this.target = target;
/**
* Stores all resolved token values for a node
*/
this.store = new Store();
/**
* All children assigned to the node
*/
this.children = [];
/**
* All values explicitly assigned to the node in their raw form
*/
this.assignedValues = new Map();
/**
* Tokens currently being reflected to CSS custom properties
*/
this.reflecting = new Set();
/**
* Binding observers for assigned and inherited derived values.
*/
this.bindingObservers = new Map();
/**
* Emits notifications to token when token values
* change the DesignTokenNode
*/
this.tokenValueChangeHandler = {
handleChange: (source, arg) => {
const token = DesignTokenImpl.getTokenById(arg);
if (token) {
// Notify any token subscribers
token.notify(this.target);
this.updateCSSTokenReflection(source, token);
}
},
};
nodeCache.set(target, this);
// Map store change notifications to token change notifications
Observable.getNotifier(this.store).subscribe(this.tokenValueChangeHandler);
if (target instanceof FASTElement) {
target.$fastController.addBehaviors([this]);
}
else if (target.isConnected) {
this.bind();
}
}
/**
* Returns a DesignTokenNode for an element.
* Creates a new instance if one does not already exist for a node,
* otherwise returns the cached instance
*
* @param target - The HTML element to retrieve a DesignTokenNode for
*/
static getOrCreate(target) {
return nodeCache.get(target) || new DesignTokenNode(target);
}
/**
* Determines if a DesignTokenNode has been created for a target
* @param target - The element to test
*/
static existsFor(target) {
return nodeCache.has(target);
}
/**
* Searches for and return the nearest parent DesignTokenNode.
* Null is returned if no node is found or the node provided is for a default element.
*/
static findParent(node) {
if (!(defaultElement === node.target)) {
let parent = composedParent(node.target);
while (parent !== null) {
if (nodeCache.has(parent)) {
return nodeCache.get(parent);
}
parent = composedParent(parent);
}
return DesignTokenNode.getOrCreate(defaultElement);
}
return null;
}
/**
* Finds the closest node with a value explicitly assigned for a token, otherwise null.
* @param token - The token to look for
* @param start - The node to start looking for value assignment
* @returns
*/
static findClosestAssignedNode(token, start) {
let current = start;
do {
if (current.has(token)) {
return current;
}
current = current.parent
? current.parent
: current.target !== defaultElement
? DesignTokenNode.getOrCreate(defaultElement)
: null;
} while (current !== null);
return null;
}
/**
* The parent DesignTokenNode, or null.
*/
get parent() {
return childToParent.get(this) || null;
}
updateCSSTokenReflection(source, token) {
if (DesignTokenImpl.isCSSDesignToken(token)) {
const parent = this.parent;
const reflecting = this.isReflecting(token);
if (parent) {
const parentValue = parent.get(token);
const sourceValue = source.get(token);
if (parentValue !== sourceValue && !reflecting) {
this.reflectToCSS(token);
}
else if (parentValue === sourceValue && reflecting) {
this.stopReflectToCSS(token);
}
}
else if (!reflecting) {
this.reflectToCSS(token);
}
}
}
/**
* Checks if a token has been assigned an explicit value the node.
* @param token - the token to check.
*/
has(token) {
return this.assignedValues.has(token);
}
/**
* Gets the value of a token for a node
* @param token - The token to retrieve the value for
* @returns
*/
get(token) {
const value = this.store.get(token);
if (value !== undefined) {
return value;
}
const raw = this.getRaw(token);
if (raw !== undefined) {
this.hydrate(token, raw);
return this.get(token);
}
}
/**
* Retrieves the raw assigned value of a token from the nearest assigned node.
* @param token - The token to retrieve a raw value for
* @returns
*/
getRaw(token) {
var _a;
if (this.assignedValues.has(token)) {
return this.assignedValues.get(token);
}
return (_a = DesignTokenNode.findClosestAssignedNode(token, this)) === null || _a === void 0 ? void 0 : _a.getRaw(token);
}
/**
* Sets a token to a value for a node
* @param token - The token to set
* @param value - The value to set the token to
*/
set(token, value) {
if (DesignTokenImpl.isDerivedDesignTokenValue(this.assignedValues.get(token))) {
this.tearDownBindingObserver(token);
}
this.assignedValues.set(token, value);
if (DesignTokenImpl.isDerivedDesignTokenValue(value)) {
this.setupBindingObserver(token, value);
}
else {
this.store.set(token, value);
}
}
/**
* Deletes a token value for the node.
* @param token - The token to delete the value for
*/
delete(token) {
this.assignedValues.delete(token);
this.tearDownBindingObserver(token);
const upstream = this.getRaw(token);
if (upstream) {
this.hydrate(token, upstream);
}
else {
this.store.delete(token);
}
}
/**
* Invoked when the DesignTokenNode.target is attached to the document
*/
bind() {
const parent = DesignTokenNode.findParent(this);
if (parent) {
parent.appendChild(this);
}
for (const key of this.assignedValues.keys()) {
key.notify(this.target);
}
}
/**
* Invoked when the DesignTokenNode.target is detached from the document
*/
unbind() {
if (this.parent) {
const parent = childToParent.get(this);
parent.removeChild(this);
}
}
/**
* Appends a child to a parent DesignTokenNode.
* @param child - The child to append to the node
*/
appendChild(child) {
if (child.parent) {
childToParent.get(child).removeChild(child);
}
const reParent = this.children.filter(x => child.contains(x));
childToParent.set(child, this);
this.children.push(child);
reParent.forEach(x => child.appendChild(x));
Observable.getNotifier(this.store).subscribe(child);
// How can we not notify *every* subscriber?
for (const [token, value] of this.store.all()) {
child.hydrate(token, this.bindingObservers.has(token) ? this.getRaw(token) : value);
}
}
/**
* Removes a child from a node.
* @param child - The child to remove.
*/
removeChild(child) {
const childIndex = this.children.indexOf(child);
if (childIndex !== -1) {
this.children.splice(childIndex, 1);
}
Observable.getNotifier(this.store).unsubscribe(child);
return child.parent === this ? childToParent.delete(child) : false;
}
/**
* Tests whether a provided node is contained by
* the calling node.
* @param test - The node to test
*/
contains(test) {
return composedContains(this.target, test.target);
}
/**
* Instructs the node to reflect a design token for the provided token.
* @param token - The design token to reflect
*/
reflectToCSS(token) {
if (!this.isReflecting(token)) {
this.reflecting.add(token);
DesignTokenNode.cssCustomPropertyReflector.startReflection(token, this.target);
}
}
/**
* Stops reflecting a DesignToken to CSS
* @param token - The design token to stop reflecting
*/
stopReflectToCSS(token) {
if (this.isReflecting(token)) {
this.reflecting.delete(token);
DesignTokenNode.cssCustomPropertyReflector.stopReflection(token, this.target);
}
}
/**
* Determines if a token is being reflected to CSS for a node.
* @param token - The token to check for reflection
* @returns
*/
isReflecting(token) {
return this.reflecting.has(token);
}
/**
* Handle changes to upstream tokens
* @param source - The parent DesignTokenNode
* @param property - The token ID that changed
*/
handleChange(source, property) {
const token = DesignTokenImpl.getTokenById(property);
if (!token) {
return;
}
this.hydrate(token, this.getRaw(token));
this.updateCSSTokenReflection(this.store, token);
}
/**
* Hydrates a token with a DesignTokenValue, making retrieval available.
* @param token - The token to hydrate
* @param value - The value to hydrate
*/
hydrate(token, value) {
if (!this.has(token)) {
const observer = this.bindingObservers.get(token);
if (DesignTokenImpl.isDerivedDesignTokenValue(value)) {
if (observer) {
// If the binding source doesn't match, we need
// to update the binding
if (observer.source !== value) {
this.tearDownBindingObserver(token);
this.setupBindingObserver(token, value);
}
}
else {
this.setupBindingObserver(token, value);
}
}
else {
if (observer) {
this.tearDownBindingObserver(token);
}
this.store.set(token, value);
}
}
}
/**
* Sets up a binding observer for a derived token value that notifies token
* subscribers on change.
*
* @param token - The token to notify when the binding updates
* @param source - The binding source
*/
setupBindingObserver(token, source) {
const binding = new DesignTokenBindingObserver(source, token, this);
this.bindingObservers.set(token, binding);
return binding;
}
/**
* Tear down a binding observer for a token.
*/
tearDownBindingObserver(token) {
if (this.bindingObservers.has(token)) {
this.bindingObservers.get(token).disconnect();
this.bindingObservers.delete(token);
return true;
}
return false;
}
}
/**
* Responsible for reflecting tokens to CSS custom properties
*/
DesignTokenNode.cssCustomPropertyReflector = new CustomPropertyReflector();
__decorate([
observable
], DesignTokenNode.prototype, "children", void 0);
function create(nameOrConfig) {
return DesignTokenImpl.from(nameOrConfig);
}
/* eslint-enable @typescript-eslint/no-unused-vars */
/**
* Factory object for creating {@link (DesignToken:interface)} instances.
* @public
*/
const DesignToken = Object.freeze({
create,
/**
* Informs DesignToken that an HTMLElement for which tokens have
* been set has been connected to the document.
*
* The browser does not provide a reliable mechanism to observe an HTMLElement's connectedness
* in all scenarios, so invoking this method manually is necessary when:
*
* 1. Token values are set for an HTMLElement.
* 2. The HTMLElement does not inherit from FASTElement.
* 3. The HTMLElement is not connected to the document when token values are set.
*
* @param element - The element to notify
* @returns - true if notification was successful, otherwise false.
*/
notifyConnection(element) {
if (!element.isConnected || !DesignTokenNode.existsFor(element)) {
return false;
}
DesignTokenNode.getOrCreate(element).bind();
return true;
},
/**
* Informs DesignToken that an HTMLElement for which tokens have
* been set has been disconnected to the document.
*
* The browser does not provide a reliable mechanism to observe an HTMLElement's connectedness
* in all scenarios, so invoking this method manually is necessary when:
*
* 1. Token values are set for an HTMLElement.
* 2. The HTMLElement does not inherit from FASTElement.
*
* @param element - The element to notify
* @returns - true if notification was successful, otherwise false.
*/
notifyDisconnection(element) {
if (element.isConnected || !DesignTokenNode.existsFor(element)) {
return false;
}
DesignTokenNode.getOrCreate(element).unbind();
return true;
},
/**
* Registers and element or document as a DesignToken root.
* {@link CSSDesignToken | CSSDesignTokens} with default values assigned via
* {@link (DesignToken:interface).withDefault} will emit CSS custom properties to all
* registered roots.
* @param target - The root to register
*/
registerRoot(target = defaultElement) {
RootStyleSheetTarget.registerRoot(target);
},
/**
* Unregister an element or document as a DesignToken root.
* @param target - The root to deregister
*/
unregisterRoot(target = defaultElement) {
RootStyleSheetTarget.unregisterRoot(target);
},
});
/* eslint-enable @typescript-eslint/no-non-null-assertion */
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-web-utilities/dist/localization.js
/**
* Expose ltr and rtl strings
*/
var Direction;
(function (Direction) {
Direction["ltr"] = "ltr";
Direction["rtl"] = "rtl";
})(Direction || (Direction = {}));
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-blending.js
/**
* Saturate a color using LCH color space
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function saturateViaLCH(input, saturation, saturationConstant = 18) {
const lch = rgbToLCH(input);
let sat = lch.c + saturation * saturationConstant;
if (sat < 0) {
sat = 0;
}
return lchToRGB(new ColorLCH(lch.l, sat, lch.h));
}
/**
* De-saturate a color using LCH color space
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function desaturateViaLCH(input, saturation, saturationConstant = 18) {
return saturateViaLCH(input, -1 * saturation, saturationConstant);
}
/**
* Darken a color using LAB color space
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function darkenViaLAB(input, amount, darkenConstant = 18) {
const lab = rgbToLAB(input);
const darkened = lab.l - amount * darkenConstant;
return labToRGB(new ColorLAB(darkened, lab.a, lab.b));
}
/**
* Lighten a color using LAB color space
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function lightenViaLAB(input, amount, darkenConstant = 18) {
return darkenViaLAB(input, -1 * amount, darkenConstant);
}
/**
* @public
*/
function blendBurnChannel(bottom, top) {
if (top === 0.0) {
// Despite the discontinuity, other sources seem to use 0.0 here instead of 1
return 0.0;
}
return 1.0 - (1.0 - bottom) / top;
}
/**
* Blends two colors with the burn mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendBurn(bottom, top) {
return new ColorRGBA64(blendBurnChannel(bottom.r, top.r), blendBurnChannel(bottom.g, top.g), blendBurnChannel(bottom.b, top.b), 1);
}
/**
* Blends two colors
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendColor(bottom, top) {
const bottomHSL = rgbToHSL(bottom);
const topHSL = rgbToHSL(top);
if (topHSL.s === 0) {
return new ColorRGBA64(bottomHSL.l, bottomHSL.l, bottomHSL.l, 1);
}
return hslToRGB(new ColorHSL(topHSL.h, topHSL.s, bottomHSL.l));
}
/**
* @public
*/
function blendDarkenChannel(bottom, top) {
return Math.min(bottom, top);
}
/**
* Blends two colors with the darken mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendDarken(bottom, top) {
return new ColorRGBA64(blendDarkenChannel(bottom.r, top.r), blendDarkenChannel(bottom.g, top.g), blendDarkenChannel(bottom.b, top.b), 1);
}
/**
* @public
*/
function blendDodgeChannel(bottom, top) {
if (top >= 1.0) {
return 1.0;
}
const retVal = bottom / (1.0 - top);
if (retVal >= 1.0) {
return 1.0;
}
return retVal;
}
/**
* Blends two colors with the dodge mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendDodge(bottom, top) {
return new ColorRGBA64(blendDodgeChannel(bottom.r, top.r), blendDodgeChannel(bottom.g, top.g), blendDodgeChannel(bottom.b, top.b), 1);
}
/**
* @public
*/
function blendLightenChannel(bottom, top) {
return Math.max(bottom, top);
}
/**
* Blends two colors with the lighten mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendLighten(bottom, top) {
return new ColorRGBA64(blendLightenChannel(bottom.r, top.r), blendLightenChannel(bottom.g, top.g), blendLightenChannel(bottom.b, top.b), 1);
}
/**
* @public
*/
function blendMultiplyChannel(bottom, top) {
return bottom * top;
}
/**
* Blends two colors with the multiply mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendMultiply(bottom, top) {
return new color_rgba_64_ColorRGBA64(blendMultiplyChannel(bottom.r, top.r), blendMultiplyChannel(bottom.g, top.g), blendMultiplyChannel(bottom.b, top.b), 1);
}
/**
* @public
*/
function blendOverlayChannel(bottom, top) {
if (bottom < 0.5) {
return clamp(2.0 * top * bottom, 0, 1);
}
return clamp(1.0 - 2.0 * (1.0 - top) * (1.0 - bottom), 0, 1);
}
/**
* Blends two colors with the overlay mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendOverlay(bottom, top) {
return new color_rgba_64_ColorRGBA64(blendOverlayChannel(bottom.r, top.r), blendOverlayChannel(bottom.g, top.g), blendOverlayChannel(bottom.b, top.b), 1);
}
/**
* @public
*/
function blendScreenChannel(bottom, top) {
return 1.0 - (1.0 - top) * (1.0 - bottom);
}
/**
* Blends two colors with the screen mode
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blendScreen(bottom, top) {
return new ColorRGBA64(blendScreenChannel(bottom.r, top.r), blendScreenChannel(bottom.g, top.g), blendScreenChannel(bottom.b, top.b), 1);
}
/**
* Color blend modes.
* @public
*/
var ColorBlendMode;
(function (ColorBlendMode) {
ColorBlendMode[ColorBlendMode["Burn"] = 0] = "Burn";
ColorBlendMode[ColorBlendMode["Color"] = 1] = "Color";
ColorBlendMode[ColorBlendMode["Darken"] = 2] = "Darken";
ColorBlendMode[ColorBlendMode["Dodge"] = 3] = "Dodge";
ColorBlendMode[ColorBlendMode["Lighten"] = 4] = "Lighten";
ColorBlendMode[ColorBlendMode["Multiply"] = 5] = "Multiply";
ColorBlendMode[ColorBlendMode["Overlay"] = 6] = "Overlay";
ColorBlendMode[ColorBlendMode["Screen"] = 7] = "Screen";
})(ColorBlendMode || (ColorBlendMode = {}));
/**
* Blend two colors.
*
* @remarks
* The alpha channel of the input is ignored
*
* @public
*/
function blend(mode, bottom, top) {
switch (mode) {
case ColorBlendMode.Burn:
return blendBurn(bottom, top);
case ColorBlendMode.Color:
return blendColor(bottom, top);
case ColorBlendMode.Darken:
return blendDarken(bottom, top);
case ColorBlendMode.Dodge:
return blendDodge(bottom, top);
case ColorBlendMode.Lighten:
return blendLighten(bottom, top);
case ColorBlendMode.Multiply:
return blendMultiply(bottom, top);
case ColorBlendMode.Overlay:
return blendOverlay(bottom, top);
case ColorBlendMode.Screen:
return blendScreen(bottom, top);
default:
throw new Error("Unknown blend mode");
}
}
/**
* Alpha channel of bottom is ignored
* The returned color always has an alpha channel of 1
* Different programs (eg: paint.net, photoshop) will give different answers than this occasionally but within +/- 1/255 in each channel. Just depends on the details of how they round off decimals
*
* @public
*/
function computeAlphaBlend(bottom, top) {
if (top.a >= 1) {
return top;
}
else if (top.a <= 0) {
return new ColorRGBA64(bottom.r, bottom.g, bottom.b, 1);
}
const r = top.a * top.r + (1 - top.a) * bottom.r;
const g = top.a * top.g + (1 - top.a) * bottom.g;
const b = top.a * top.b + (1 - top.a) * bottom.b;
return new ColorRGBA64(r, g, b, 1);
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-interpolation.js
/**
* Interpolate by RGB color space
*
* @public
*/
function interpolateRGB(position, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
return new color_rgba_64_ColorRGBA64(lerp(position, left.r, right.r), lerp(position, left.g, right.g), lerp(position, left.b, right.b), lerp(position, left.a, right.a));
}
/**
* Interpolate by HSL color space
*
* @public
*/
function interpolateHSL(position, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
return new color_hsl_ColorHSL(lerpAnglesInDegrees(position, left.h, right.h), lerp(position, left.s, right.s), lerp(position, left.l, right.l));
}
/**
* Interpolate by HSV color space
*
* @public
*/
function interpolateHSV(position, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
return new ColorHSV(lerpAnglesInDegrees(position, left.h, right.h), lerp(position, left.s, right.s), lerp(position, left.v, right.v));
}
/**
* Interpolate by XYZ color space
*
* @public
*/
function interpolateXYZ(position, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
return new ColorXYZ(lerp(position, left.x, right.x), lerp(position, left.y, right.y), lerp(position, left.z, right.z));
}
/**
* Interpolate by LAB color space
*
* @public
*/
function interpolateLAB(position, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
return new color_lab_ColorLAB(lerp(position, left.l, right.l), lerp(position, left.a, right.a), lerp(position, left.b, right.b));
}
/**
* Interpolate by LCH color space
*
* @public
*/
function interpolateLCH(position, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
return new ColorLCH(lerp(position, left.l, right.l), lerp(position, left.c, right.c), lerpAnglesInDegrees(position, left.h, right.h));
}
/**
* Color interpolation spaces
*
* @public
*/
var ColorInterpolationSpace;
(function (ColorInterpolationSpace) {
ColorInterpolationSpace[ColorInterpolationSpace["RGB"] = 0] = "RGB";
ColorInterpolationSpace[ColorInterpolationSpace["HSL"] = 1] = "HSL";
ColorInterpolationSpace[ColorInterpolationSpace["HSV"] = 2] = "HSV";
ColorInterpolationSpace[ColorInterpolationSpace["XYZ"] = 3] = "XYZ";
ColorInterpolationSpace[ColorInterpolationSpace["LAB"] = 4] = "LAB";
ColorInterpolationSpace[ColorInterpolationSpace["LCH"] = 5] = "LCH";
})(ColorInterpolationSpace || (ColorInterpolationSpace = {}));
/**
* Interpolate by color space
*
* @public
*/
function interpolateByColorSpace(position, space, left, right) {
if (isNaN(position) || position <= 0) {
return left;
}
else if (position >= 1) {
return right;
}
switch (space) {
case ColorInterpolationSpace.HSL:
return color_converters_hslToRGB(interpolateHSL(position, color_converters_rgbToHSL(left), color_converters_rgbToHSL(right)));
case ColorInterpolationSpace.HSV:
return hsvToRGB(interpolateHSV(position, rgbToHSV(left), rgbToHSV(right)));
case ColorInterpolationSpace.XYZ:
return xyzToRGB(interpolateXYZ(position, rgbToXYZ(left), rgbToXYZ(right)));
case ColorInterpolationSpace.LAB:
return color_converters_labToRGB(interpolateLAB(position, color_converters_rgbToLAB(left), color_converters_rgbToLAB(right)));
case ColorInterpolationSpace.LCH:
return lchToRGB(interpolateLCH(position, rgbToLCH(left), rgbToLCH(right)));
default:
return interpolateRGB(position, left, right);
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-scale.js
/**
* A color scale created from linear stops
* @public
*/
class color_scale_ColorScale {
constructor(stops) {
if (stops == null || stops.length === 0) {
throw new Error("The stops argument must be non-empty");
}
else {
this.stops = this.sortColorScaleStops(stops);
}
}
static createBalancedColorScale(colors) {
if (colors == null || colors.length === 0) {
throw new Error("The colors argument must be non-empty");
}
const stops = new Array(colors.length);
for (let i = 0; i < colors.length; i++) {
// Special case first and last in order to avoid floating point jaggies
if (i === 0) {
stops[i] = { color: colors[i], position: 0 };
}
else if (i === colors.length - 1) {
stops[i] = { color: colors[i], position: 1 };
}
else {
stops[i] = {
color: colors[i],
position: i * (1 / (colors.length - 1)),
};
}
}
return new color_scale_ColorScale(stops);
}
getColor(position, interpolationMode = ColorInterpolationSpace.RGB) {
if (this.stops.length === 1) {
return this.stops[0].color;
}
else if (position <= 0) {
return this.stops[0].color;
}
else if (position >= 1) {
return this.stops[this.stops.length - 1].color;
}
let lowerIndex = 0;
for (let i = 0; i < this.stops.length; i++) {
if (this.stops[i].position <= position) {
lowerIndex = i;
}
}
let upperIndex = lowerIndex + 1;
if (upperIndex >= this.stops.length) {
upperIndex = this.stops.length - 1;
}
const scalePosition = (position - this.stops[lowerIndex].position) *
(1.0 / (this.stops[upperIndex].position - this.stops[lowerIndex].position));
return interpolateByColorSpace(scalePosition, interpolationMode, this.stops[lowerIndex].color, this.stops[upperIndex].color);
}
trim(lowerBound, upperBound, interpolationMode = ColorInterpolationSpace.RGB) {
if (lowerBound < 0 || upperBound > 1 || upperBound < lowerBound) {
throw new Error("Invalid bounds");
}
if (lowerBound === upperBound) {
return new color_scale_ColorScale([
{ color: this.getColor(lowerBound, interpolationMode), position: 0 },
]);
}
const containedStops = [];
for (let i = 0; i < this.stops.length; i++) {
if (this.stops[i].position >= lowerBound &&
this.stops[i].position <= upperBound) {
containedStops.push(this.stops[i]);
}
}
if (containedStops.length === 0) {
return new color_scale_ColorScale([
{ color: this.getColor(lowerBound), position: lowerBound },
{ color: this.getColor(upperBound), position: upperBound },
]);
}
if (containedStops[0].position !== lowerBound) {
containedStops.unshift({
color: this.getColor(lowerBound),
position: lowerBound,
});
}
if (containedStops[containedStops.length - 1].position !== upperBound) {
containedStops.push({
color: this.getColor(upperBound),
position: upperBound,
});
}
const range = upperBound - lowerBound;
const finalStops = new Array(containedStops.length);
for (let i = 0; i < containedStops.length; i++) {
finalStops[i] = {
color: containedStops[i].color,
position: (containedStops[i].position - lowerBound) / range,
};
}
return new color_scale_ColorScale(finalStops);
}
findNextColor(position, contrast, searchDown = false, interpolationMode = ColorInterpolationSpace.RGB, contrastErrorMargin = 0.005, maxSearchIterations = 32) {
if (isNaN(position) || position <= 0) {
position = 0;
}
else if (position >= 1) {
position = 1;
}
const startingColor = this.getColor(position, interpolationMode);
const finalPosition = searchDown ? 0 : 1;
const finalColor = this.getColor(finalPosition, interpolationMode);
const finalContrast = contrastRatio(startingColor, finalColor);
if (finalContrast <= contrast) {
return finalPosition;
}
let testRangeMin = searchDown ? 0 : position;
let testRangeMax = searchDown ? position : 0;
let mid = finalPosition;
let iterations = 0;
while (iterations <= maxSearchIterations) {
mid = Math.abs(testRangeMax - testRangeMin) / 2 + testRangeMin;
const midColor = this.getColor(mid, interpolationMode);
const midContrast = contrastRatio(startingColor, midColor);
if (Math.abs(midContrast - contrast) <= contrastErrorMargin) {
return mid;
}
else if (midContrast > contrast) {
if (searchDown) {
testRangeMin = mid;
}
else {
testRangeMax = mid;
}
}
else {
if (searchDown) {
testRangeMax = mid;
}
else {
testRangeMin = mid;
}
}
iterations++;
}
return mid;
}
clone() {
const newStops = new Array(this.stops.length);
for (let i = 0; i < newStops.length; i++) {
newStops[i] = {
color: this.stops[i].color,
position: this.stops[i].position,
};
}
return new color_scale_ColorScale(newStops);
}
sortColorScaleStops(stops) {
return stops.sort((a, b) => {
const A = a.position;
const B = b.position;
if (A < B) {
return -1;
}
else if (A > B) {
return 1;
}
else {
return 0;
}
});
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/color-palette.js
/**
* Generates a color palette
* @public
*/
class ColorPalette {
constructor(config) {
this.config = Object.assign({}, ColorPalette.defaultPaletteConfig, config);
this.palette = [];
this.updatePaletteColors();
}
updatePaletteGenerationValues(newConfig) {
let changed = false;
for (const key in newConfig) {
if (this.config[key]) {
if (this.config[key].equalValue) {
if (!this.config[key].equalValue(newConfig[key])) {
this.config[key] = newConfig[key];
changed = true;
}
}
else {
if (newConfig[key] !== this.config[key]) {
this.config[key] = newConfig[key];
changed = true;
}
}
}
}
if (changed) {
this.updatePaletteColors();
}
return changed;
}
updatePaletteColors() {
const scale = this.generatePaletteColorScale();
for (let i = 0; i < this.config.steps; i++) {
this.palette[i] = scale.getColor(i / (this.config.steps - 1), this.config.interpolationMode);
}
}
generatePaletteColorScale() {
// Even when config.baseScalePosition is specified, using 0.5 for the baseColor
// in the baseScale gives better results. Otherwise very off-center palettes
// tend to go completely grey at the end furthest from the specified base color.
const baseColorHSL = color_converters_rgbToHSL(this.config.baseColor);
const baseScale = new color_scale_ColorScale([
{ position: 0, color: this.config.scaleColorLight },
{ position: 0.5, color: this.config.baseColor },
{ position: 1, color: this.config.scaleColorDark },
]);
const trimmedScale = baseScale.trim(this.config.clipLight, 1 - this.config.clipDark);
const trimmedLight = trimmedScale.getColor(0);
const trimmedDark = trimmedScale.getColor(1);
let adjustedLight = trimmedLight;
let adjustedDark = trimmedDark;
if (baseColorHSL.s >= this.config.saturationAdjustmentCutoff) {
adjustedLight = saturateViaLCH(adjustedLight, this.config.saturationLight);
adjustedDark = saturateViaLCH(adjustedDark, this.config.saturationDark);
}
if (this.config.multiplyLight !== 0) {
const multiply = blendMultiply(this.config.baseColor, adjustedLight);
adjustedLight = interpolateByColorSpace(this.config.multiplyLight, this.config.interpolationMode, adjustedLight, multiply);
}
if (this.config.multiplyDark !== 0) {
const multiply = blendMultiply(this.config.baseColor, adjustedDark);
adjustedDark = interpolateByColorSpace(this.config.multiplyDark, this.config.interpolationMode, adjustedDark, multiply);
}
if (this.config.overlayLight !== 0) {
const overlay = blendOverlay(this.config.baseColor, adjustedLight);
adjustedLight = interpolateByColorSpace(this.config.overlayLight, this.config.interpolationMode, adjustedLight, overlay);
}
if (this.config.overlayDark !== 0) {
const overlay = blendOverlay(this.config.baseColor, adjustedDark);
adjustedDark = interpolateByColorSpace(this.config.overlayDark, this.config.interpolationMode, adjustedDark, overlay);
}
if (this.config.baseScalePosition) {
if (this.config.baseScalePosition <= 0) {
return new color_scale_ColorScale([
{ position: 0, color: this.config.baseColor },
{ position: 1, color: adjustedDark.clamp() },
]);
}
else if (this.config.baseScalePosition >= 1) {
return new color_scale_ColorScale([
{ position: 0, color: adjustedLight.clamp() },
{ position: 1, color: this.config.baseColor },
]);
}
return new color_scale_ColorScale([
{ position: 0, color: adjustedLight.clamp() },
{
position: this.config.baseScalePosition,
color: this.config.baseColor,
},
{ position: 1, color: adjustedDark.clamp() },
]);
}
return new color_scale_ColorScale([
{ position: 0, color: adjustedLight.clamp() },
{ position: 0.5, color: this.config.baseColor },
{ position: 1, color: adjustedDark.clamp() },
]);
}
}
ColorPalette.defaultPaletteConfig = {
baseColor: parseColorHexRGB("#808080"),
steps: 11,
interpolationMode: ColorInterpolationSpace.RGB,
scaleColorLight: new color_rgba_64_ColorRGBA64(1, 1, 1, 1),
scaleColorDark: new color_rgba_64_ColorRGBA64(0, 0, 0, 1),
clipLight: 0.185,
clipDark: 0.16,
saturationAdjustmentCutoff: 0.05,
saturationLight: 0.35,
saturationDark: 1.25,
overlayLight: 0,
overlayDark: 0.25,
multiplyLight: 0,
multiplyDark: 0,
baseScalePosition: 0.5,
};
ColorPalette.greyscalePaletteConfig = {
baseColor: parseColorHexRGB("#808080"),
steps: 11,
interpolationMode: ColorInterpolationSpace.RGB,
scaleColorLight: new color_rgba_64_ColorRGBA64(1, 1, 1, 1),
scaleColorDark: new color_rgba_64_ColorRGBA64(0, 0, 0, 1),
clipLight: 0,
clipDark: 0,
saturationAdjustmentCutoff: 0,
saturationLight: 0,
saturationDark: 0,
overlayLight: 0,
overlayDark: 0,
multiplyLight: 0,
multiplyDark: 0,
baseScalePosition: 0.5,
};
/**
* Takes the input color and compares it to each color in the reference array to find the index with the closest Lightness value in HSL color space
* @public
*/
function matchLightnessIndex(input, reference) {
const hsl = rgbToHSL(input);
let bestFitValue = Number.MAX_VALUE;
let bestFitIndex = 0;
for (let i = 0; i < reference.length; i++) {
const ihsl = rgbToHSL(reference[i]);
const fitValue = Math.abs(ihsl.l - hsl.l);
if (fitValue < bestFitValue) {
bestFitValue = fitValue;
bestFitIndex = i;
}
}
return bestFitIndex;
}
/**
* Generates a greyscale palette using greyscaleConfig. The Lightness (in HSL) of the input color is then compared to the greyscale palette to determine how far off center the input color should be placed. The output palette is then generated with outputSteps number of steps using colorConfig.
* @public
*/
function generateOffCenterPalette(input, outputSteps, greyscaleConfig = ColorPalette.greyscalePaletteConfig, colorConfig = ColorPalette.defaultPaletteConfig) {
const greyscale = new ColorPalette(Object.assign(Object.assign({}, greyscaleConfig), { steps: outputSteps }));
const scaleIndex = matchLightnessIndex(input, greyscale.palette);
return new ColorPalette(Object.assign(Object.assign({}, colorConfig), { steps: outputSteps, baseColor: input, baseScalePosition: scaleIndex / (outputSteps - 1) }));
}
/**
* Take the input array of colors and extrapolates them to a larger palette of size targetSize. If preserveInputColors is false the input colors are evenly distributed into the output. Otherwise, the positions of the input colors are adjusted from a perfectly even distribution in order to ensure that the exact color values appearing in the input array also appear in the output array. The larger targetSize is compared to input.length the smaller those adjustments will be.
*
* @public
*/
function rescale(input, targetSize, preserveInputColors) {
if (input.length <= 1 || targetSize <= 1) {
throw new Error("The input array and targetSize must both be greater than 1");
}
if (preserveInputColors && targetSize <= input.length) {
throw new Error("If preserveInputColors is true then targetSize must be greater than the length of the input array");
}
const stops = new Array(input.length);
if (preserveInputColors) {
for (let i = 0; i < input.length; i++) {
const p = i / (input.length - 1);
let bestFitValue = 2;
let bestFitIndex = 0;
for (let j = 0; j < targetSize; j++) {
const fitValue = Math.abs(j / (targetSize - 1) - p);
if (fitValue < bestFitValue) {
bestFitValue = fitValue;
bestFitIndex = j;
}
if (fitValue === 0) {
break;
}
}
stops[i] = {
color: input[i],
position: bestFitIndex / (targetSize - 1),
};
}
}
else {
for (let i = 0; i < stops.length; i++) {
stops[i] = { color: input[i], position: i / (input.length - 1) };
}
}
const scale = new ColorScale(stops);
const retVal = new Array(targetSize);
for (let i = 0; i < targetSize; i++) {
retVal[i] = scale.getColor(i / (targetSize - 1));
}
return retVal;
}
/**
* @public
*/
const defaultCenteredRescaleConfig = {
targetSize: 63,
spacing: 4,
scaleColorLight: ColorPalette.defaultPaletteConfig.scaleColorLight,
scaleColorDark: ColorPalette.defaultPaletteConfig.scaleColorDark,
};
/**
* Takes an input array of colors and extrapolates them to a larger palette. The mapping first takes the input array and extrapolates between each color so that they are separated by spacing-1 slots. Then it adds to either end enough new colors to make up the desired targetSize. All output color slots between the defined stops are interpolated.
* @example
* For an input array with length 5, a targetSize of 17 and spacing of 3 the output would be:
* 0: scaleColorLight
* 1:
* 2: input 0
* 3:
* 4:
* 5: input 1
* 6:
* 7:
* 8: input 2
* 9:
* 10:
* 11: input 3
* 12:
* 13:
* 14: input 4
* 15:
* 16: scaleColorDark
*
* @public
*/
function centeredRescale(input, config = defaultCenteredRescaleConfig) {
if (input.length === 0) {
return [];
}
const offset = Math.floor((config.targetSize - ((input.length - 1) * config.spacing + 1)) / 2);
if (offset < 0) {
throw new Error("(targetSize - ((input.length - 1) * spacing + 1)) / 2 must be >= 0");
}
const stops = new Array(input.length + 2);
stops[0] = { position: 0, color: config.scaleColorLight };
stops[stops.length - 1] = {
position: 1,
color: config.scaleColorDark,
};
for (let i = 0; i < input.length; i++) {
stops[i + 1] = {
color: input[i],
position: (i * config.spacing + offset) / (config.targetSize - 1),
};
}
const scale = new ColorScale(stops);
const retVal = new Array(config.targetSize);
for (let i = 0; i < config.targetSize; i++) {
retVal[i] = scale.getColor(i / (config.targetSize - 1));
}
return retVal;
}
/**
* Generates two palettes of length shortPaletteLength and longPaletteLength from a base color. The base color is compared to the default greyscale palette to determine where it should be placed. The short palette is then fed into centeredRescale to create the long palette. The colors in the short palette are always contained within the long.
* @public
*/
function generateScaledPalettes(input, shortPaletteLength = 11, config = defaultCenteredRescaleConfig) {
const shortPalette = generateOffCenterPalette(input, shortPaletteLength);
const longPalette = centeredRescale(shortPalette.palette, config);
return { short: shortPalette.palette, long: longPalette };
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-colors/dist/component-state-color-palette.js
/**
* Creates a color palette for UI components
* @public
*/
class ComponentStateColorPalette {
constructor(config) {
this.palette = [];
this.config = Object.assign({}, ComponentStateColorPalette.defaultPaletteConfig, config);
this.regenPalettes();
}
regenPalettes() {
let steps = this.config.steps;
if (isNaN(steps) || steps < 3) {
steps = 3;
}
// This palette is tuned to go as dark as differences between the levels can be perceived according to tests
// on numerous monitors in different conditions. Stay linear from white until this first cutoff.
const darkLum = 0.14;
// In the dark compression, this is the last luminance value before full black.
const darkestLum = 0.06;
// The Color for the luminance value above, placed on the ramp at it's normal position, so darker colors after
// it can be compressed.
const darkLumColor = new color_rgba_64_ColorRGBA64(darkLum, darkLum, darkLum, 1);
// The number of steps in the ramp that has been tuned for default use. This coincides with the size of the
// default ramp, but the palette could be generated with fewer steps to increase final contrast. This number
// should however stay the same.
const stepsForLuminanceRamp = 94;
// Create the reference, dark-compressed, grey palette, like:
// F------------------------------------------------------------------------------------[dark]------[darkest]0
// |--compressed area--|
const r = new ColorPalette(Object.assign(Object.assign({}, ColorPalette.greyscalePaletteConfig), { baseColor: darkLumColor, baseScalePosition: ((1 - darkLum) * 100) / stepsForLuminanceRamp, steps }));
const referencePalette = r.palette;
// Find the requested base color on the adjusted luminance reference ramp.
// There is no _right_ way to desaturate a color, and both methods we've tested have value, so average them out.
const baseColorLum1 = rgbToLinearLuminance(this.config.baseColor);
const baseColorLum2 = color_converters_rgbToHSL(this.config.baseColor).l;
const baseColorLum = (baseColorLum1 + baseColorLum2) / 2;
const baseColorRefIndex = this.matchRelativeLuminanceIndex(baseColorLum, referencePalette);
const baseColorPercent = baseColorRefIndex / (steps - 1);
// Find the luminance location for the dark cutoff.
const darkRefIndex = this.matchRelativeLuminanceIndex(darkLum, referencePalette);
const darkPercent = darkRefIndex / (steps - 1);
// Issue https://github.com/microsoft/fast/issues/1904
// Creating a color from H, S, and a known L value is not the inverse of getting the relative
// luminace as above. Need to derive a relative luminance version of the color to better match on the dark end.
// Find the dark cutoff and darkest variations of the requested base color.
const baseColorHSL = color_converters_rgbToHSL(this.config.baseColor);
const darkBaseColor = color_converters_hslToRGB(color_hsl_ColorHSL.fromObject({
h: baseColorHSL.h,
s: baseColorHSL.s,
l: darkLum,
}));
const darkestBaseColor = color_converters_hslToRGB(color_hsl_ColorHSL.fromObject({
h: baseColorHSL.h,
s: baseColorHSL.s,
l: darkestLum,
}));
// Create the gradient stops, including the base color and anchor colors for the dark end compression.
const fullColorScaleStops = new Array(5);
fullColorScaleStops[0] = {
position: 0,
color: new color_rgba_64_ColorRGBA64(1, 1, 1, 1),
};
fullColorScaleStops[1] = {
position: baseColorPercent,
color: this.config.baseColor,
};
fullColorScaleStops[2] = {
position: darkPercent,
color: darkBaseColor,
};
fullColorScaleStops[3] = {
position: 0.99,
color: darkestBaseColor,
};
fullColorScaleStops[4] = {
position: 1,
color: new color_rgba_64_ColorRGBA64(0, 0, 0, 1),
};
const scale = new color_scale_ColorScale(fullColorScaleStops);
// Create the palette.
this.palette = new Array(steps);
for (let i = 0; i < steps; i++) {
const c = scale.getColor(i / (steps - 1), ColorInterpolationSpace.RGB);
this.palette[i] = c;
}
}
matchRelativeLuminanceIndex(input, reference) {
let bestFitValue = Number.MAX_VALUE;
let bestFitIndex = 0;
let i = 0;
const referenceLength = reference.length;
for (; i < referenceLength; i++) {
const fitValue = Math.abs(rgbToLinearLuminance(reference[i]) - input);
if (fitValue < bestFitValue) {
bestFitValue = fitValue;
bestFitIndex = i;
}
}
return bestFitIndex;
}
}
ComponentStateColorPalette.defaultPaletteConfig = {
baseColor: parseColorHexRGB("#808080"),
steps: 94,
};
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/utilities/binary-search.js
/**
* @internal
*/
function binarySearch(valuesToSearch, searchCondition, startIndex = 0, endIndex = valuesToSearch.length - 1) {
if (endIndex === startIndex) {
return valuesToSearch[startIndex];
}
const middleIndex = Math.floor((endIndex - startIndex) / 2) + startIndex;
// Check to see if this passes on the item in the center of the array
// if it does check the previous values
return searchCondition(valuesToSearch[middleIndex])
? binarySearch(valuesToSearch, searchCondition, startIndex, middleIndex // include this index because it passed the search condition
)
: binarySearch(valuesToSearch, searchCondition, middleIndex + 1, // exclude this index because it failed the search condition
endIndex);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/utilities/direction-by-is-dark.js
/**
* @internal
*/
function directionByIsDark(color) {
return isDark(color) ? -1 : 1;
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/palette.js
function palette_create(rOrSource, g, b) {
if (typeof rOrSource === 'number') {
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
return PaletteRGB.from(SwatchRGB.create(rOrSource, g, b));
}
else {
return PaletteRGB.from(rOrSource);
}
}
function from(source) {
return isSwatchRGB(source)
? PaletteRGBImpl.from(source)
: PaletteRGBImpl.from(SwatchRGB.create(source.r, source.g, source.b));
}
/** @public */
const PaletteRGB = Object.freeze({
create: palette_create,
from
});
/**
* A {@link Palette} representing RGB swatch values.
* @public
*/
class PaletteRGBImpl {
/**
*
* @param source - The source color for the palette
* @param swatches - All swatches in the palette
*/
constructor(source, swatches) {
this.closestIndexCache = new Map();
this.source = source;
this.swatches = swatches;
this.reversedSwatches = Object.freeze([...this.swatches].reverse());
this.lastIndex = this.swatches.length - 1;
}
/**
* {@inheritdoc Palette.colorContrast}
*/
colorContrast(reference, contrastTarget, initialSearchIndex, direction) {
if (initialSearchIndex === undefined) {
initialSearchIndex = this.closestIndexOf(reference);
}
let source = this.swatches;
const endSearchIndex = this.lastIndex;
let startSearchIndex = initialSearchIndex;
if (direction === undefined) {
direction = directionByIsDark(reference);
}
const condition = (value) => contrast(reference, value) >= contrastTarget;
if (direction === -1) {
source = this.reversedSwatches;
startSearchIndex = endSearchIndex - startSearchIndex;
}
return binarySearch(source, condition, startSearchIndex, endSearchIndex);
}
/**
* {@inheritdoc Palette.get}
*/
get(index) {
return (this.swatches[index] || this.swatches[clamp(index, 0, this.lastIndex)]);
}
/**
* {@inheritdoc Palette.closestIndexOf}
*/
closestIndexOf(reference) {
if (this.closestIndexCache.has(reference.relativeLuminance)) {
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
return this.closestIndexCache.get(reference.relativeLuminance);
}
let index = this.swatches.indexOf(reference);
if (index !== -1) {
this.closestIndexCache.set(reference.relativeLuminance, index);
return index;
}
const closest = this.swatches.reduce((previous, next) => Math.abs(next.relativeLuminance - reference.relativeLuminance) <
Math.abs(previous.relativeLuminance - reference.relativeLuminance)
? next
: previous);
index = this.swatches.indexOf(closest);
this.closestIndexCache.set(reference.relativeLuminance, index);
return index;
}
/**
* Create a color palette from a provided swatch
* @param source - The source swatch to create a palette from
* @returns
*/
static from(source) {
return new PaletteRGBImpl(source, Object.freeze(new ComponentStateColorPalette({
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
baseColor: color_rgba_64_ColorRGBA64.fromObject(source)
}).palette.map(x => {
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
const _x = parseColorHexRGB(x.toStringHexRGB());
return SwatchRGB.create(_x.r, _x.g, _x.b);
})));
}
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/accent-fill.js
/**
* @internal
*/
function accentFill(palette, neutralPalette, reference, hoverDelta, activeDelta, focusDelta, neutralFillRestDelta, neutralFillHoverDelta, neutralFillActiveDelta) {
const accent = palette.source;
const referenceIndex = neutralPalette.closestIndexOf(reference);
const swapThreshold = Math.max(neutralFillRestDelta, neutralFillHoverDelta, neutralFillActiveDelta);
const direction = referenceIndex >= swapThreshold ? -1 : 1;
const accentIndex = palette.closestIndexOf(accent);
const hoverIndex = accentIndex;
const restIndex = hoverIndex + direction * -1 * hoverDelta;
const activeIndex = restIndex + direction * activeDelta;
const focusIndex = restIndex + direction * focusDelta;
return {
rest: palette.get(restIndex),
hover: palette.get(hoverIndex),
active: palette.get(activeIndex),
focus: palette.get(focusIndex)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/accent-foreground.js
/**
* @internal
*/
function accentForeground(palette, reference, contrastTarget, restDelta, hoverDelta, activeDelta, focusDelta) {
const accent = palette.source;
const accentIndex = palette.closestIndexOf(accent);
const direction = directionByIsDark(reference);
const startIndex = accentIndex +
(direction === 1
? Math.min(restDelta, hoverDelta)
: Math.max(direction * restDelta, direction * hoverDelta));
const accessibleSwatch = palette.colorContrast(reference, contrastTarget, startIndex, direction);
const accessibleIndex1 = palette.closestIndexOf(accessibleSwatch);
const accessibleIndex2 = accessibleIndex1 + direction * Math.abs(restDelta - hoverDelta);
const indexOneIsRestState = direction === 1
? restDelta < hoverDelta
: direction * restDelta > direction * hoverDelta;
let restIndex;
let hoverIndex;
if (indexOneIsRestState) {
restIndex = accessibleIndex1;
hoverIndex = accessibleIndex2;
}
else {
restIndex = accessibleIndex2;
hoverIndex = accessibleIndex1;
}
return {
rest: palette.get(restIndex),
hover: palette.get(hoverIndex),
active: palette.get(restIndex + direction * activeDelta),
focus: palette.get(restIndex + direction * focusDelta)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/utilities/color-constants.js
/**
* @internal
*/
const white = SwatchRGB.create(1, 1, 1);
/**
* @internal
*/
const black = SwatchRGB.create(0, 0, 0);
/**
* @internal
*/
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
const middleGrey = SwatchRGB.from(parseColorHexRGB('#808080'));
/**
* @internal
*/
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
const accentBase = SwatchRGB.from(parseColorHexRGB('#DA1A5F'));
/**
* @internal
*/
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
const errorBase = SwatchRGB.from(parseColorHexRGB('#D32F2F'));
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/foreground-on-accent.js
/**
* @internal
*/
function foregroundOnAccent(reference, contrastTarget) {
return reference.contrast(white) >= contrastTarget ? white : black;
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-fill.js
/**
*
* @param palette - The palette to operate on
* @param reference - The reference color to calculate a color for
* @param delta - The offset from the reference's location
* @param threshold - Determines if a lighter or darker color than the reference will be picked.
* @returns
*
* @internal
*/
function neutralFill(palette, reference, restDelta, hoverDelta, activeDelta, focusDelta) {
const referenceIndex = palette.closestIndexOf(reference);
const threshold = Math.max(restDelta, hoverDelta, activeDelta, focusDelta);
const direction = referenceIndex >= threshold ? -1 : 1;
return {
rest: palette.get(referenceIndex + direction * restDelta),
hover: palette.get(referenceIndex + direction * hoverDelta),
active: palette.get(referenceIndex + direction * activeDelta),
focus: palette.get(referenceIndex + direction * focusDelta)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-fill-input.js
/**
* @internal
*/
function neutralFillInput(palette, reference, restDelta, hoverDelta, activeDelta, focusDelta) {
const direction = directionByIsDark(reference);
const referenceIndex = palette.closestIndexOf(reference);
return {
rest: palette.get(referenceIndex - direction * restDelta),
hover: palette.get(referenceIndex - direction * hoverDelta),
active: palette.get(referenceIndex - direction * activeDelta),
focus: palette.get(referenceIndex - direction * focusDelta)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-fill-layer.js
/**
* @internal
*/
function neutralFillLayer(palette, reference, delta) {
const referenceIndex = palette.closestIndexOf(reference);
return palette.get(referenceIndex - (referenceIndex < delta ? delta * -1 : delta));
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-fill-stealth.js
/**
* @internal
*/
function neutralFillStealth(palette, reference, restDelta, hoverDelta, activeDelta, focusDelta, fillRestDelta, fillHoverDelta, fillActiveDelta, fillFocusDelta) {
const swapThreshold = Math.max(restDelta, hoverDelta, activeDelta, focusDelta, fillRestDelta, fillHoverDelta, fillActiveDelta, fillFocusDelta);
const referenceIndex = palette.closestIndexOf(reference);
const direction = referenceIndex >= swapThreshold ? -1 : 1;
return {
rest: palette.get(referenceIndex + direction * restDelta),
hover: palette.get(referenceIndex + direction * hoverDelta),
active: palette.get(referenceIndex + direction * activeDelta),
focus: palette.get(referenceIndex + direction * focusDelta)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-fill-contrast.js
/**
* @internal
*/
function neutralFillContrast(palette, reference, restDelta, hoverDelta, activeDelta, focusDelta) {
const direction = directionByIsDark(reference);
const accessibleIndex = palette.closestIndexOf(palette.colorContrast(reference, 4.5));
const accessibleIndex2 = accessibleIndex + direction * Math.abs(restDelta - hoverDelta);
const indexOneIsRest = direction === 1
? restDelta < hoverDelta
: direction * restDelta > direction * hoverDelta;
let restIndex;
let hoverIndex;
if (indexOneIsRest) {
restIndex = accessibleIndex;
hoverIndex = accessibleIndex2;
}
else {
restIndex = accessibleIndex2;
hoverIndex = accessibleIndex;
}
return {
rest: palette.get(restIndex),
hover: palette.get(hoverIndex),
active: palette.get(restIndex + direction * activeDelta),
focus: palette.get(restIndex + direction * focusDelta)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/focus-stroke.js
/** @internal */
function focusStrokeOuter(palette, reference) {
return palette.colorContrast(reference, 3.5);
}
/** @internal */
function focusStrokeInner(palette, reference, focusColor) {
return palette.colorContrast(focusColor, 3.5, palette.closestIndexOf(palette.source), (directionByIsDark(reference) * -1));
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-foreground.js
/**
* @internal
*/
function neutralForeground(palette, reference) {
return palette.colorContrast(reference, 14);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-foreground-hint.js
/**
* The neutralForegroundHint color recipe
* @param palette - The palette to operate on
* @param reference - The reference color
*
* @internal
*/
function neutralForegroundHint(palette, reference) {
return palette.colorContrast(reference, 4.5);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-layer-card-container.js
/**
* @internal
*/
function neutralLayerCardContainer(palette, relativeLuminance, layerDelta) {
return palette.get(palette.closestIndexOf(baseLayerLuminanceSwatch(relativeLuminance)) +
layerDelta);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-layer-floating.js
/**
* @internal
*/
function neutralLayerFloating(palette, relativeLuminance, layerDelta) {
const cardIndex = palette.closestIndexOf(baseLayerLuminanceSwatch(relativeLuminance)) -
layerDelta;
return palette.get(cardIndex - layerDelta);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-layer-1.js
function neutralLayer1(palette, baseLayerLuminance) {
return palette.get(palette.closestIndexOf(baseLayerLuminanceSwatch(baseLayerLuminance)));
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-layer-2.js
/**
* @internal
*/
function neutralLayer2Index(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta) {
return Math.max(palette.closestIndexOf(baseLayerLuminanceSwatch(luminance)) + layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta);
}
/**
* @internal
*/
function neutralLayer2(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta) {
return palette.get(neutralLayer2Index(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta));
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-layer-3.js
/**
* @internal
*/
function neutralLayer3(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta) {
return palette.get(neutralLayer2Index(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta) + layerDelta);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-layer-4.js
/**
* @internal
*/
function neutralLayer4(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta) {
return palette.get(neutralLayer2Index(palette, luminance, layerDelta, fillRestDelta, fillHoverDelta, fillActiveDelta) +
layerDelta * 2);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-stroke.js
/**
* @internal
*/
function neutralStroke(palette, reference, restDelta, hoverDelta, activeDelta, focusDelta) {
const referenceIndex = palette.closestIndexOf(reference);
const direction = directionByIsDark(reference);
const restIndex = referenceIndex + direction * restDelta;
const hoverIndex = restIndex + direction * (hoverDelta - restDelta);
const activeIndex = restIndex + direction * (activeDelta - restDelta);
const focusIndex = restIndex + direction * (focusDelta - restDelta);
return {
rest: palette.get(restIndex),
hover: palette.get(hoverIndex),
active: palette.get(activeIndex),
focus: palette.get(focusIndex)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/neutral-stroke-divider.js
/**
* The neutralStrokeDivider color recipe
* @param palette - The palette to operate on
* @param reference - The reference color
* @param delta - The offset from the reference
*
* @internal
*/
function neutralStrokeDivider(palette, reference, delta) {
return palette.get(palette.closestIndexOf(reference) + directionByIsDark(reference) * delta);
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/error-fill.js
function errorFillAlgorithm(palette, neutralPalette, reference, hoverDelta, activeDelta, focusDelta, neutralFillRestDelta, neutralFillHoverDelta, neutralFillActiveDelta) {
const error = palette.source;
const referenceIndex = neutralPalette.closestIndexOf(reference);
const swapThreshold = Math.max(neutralFillRestDelta, neutralFillHoverDelta, neutralFillActiveDelta);
const direction = referenceIndex >= swapThreshold ? -1 : 1;
const errorIndex = palette.closestIndexOf(error);
const hoverIndex = errorIndex;
const restIndex = hoverIndex + direction * -1 * hoverDelta;
const activeIndex = restIndex + direction * activeDelta;
const focusIndex = restIndex + direction * focusDelta;
return {
rest: palette.get(restIndex),
hover: palette.get(hoverIndex),
active: palette.get(activeIndex),
focus: palette.get(focusIndex)
};
}
/**
* @internal
*/
function errorForegroundAlgorithm(palette, reference, contrastTarget, restDelta, hoverDelta, activeDelta, focusDelta) {
const error = palette.source;
const errorIndex = palette.closestIndexOf(error);
const direction = isDark(reference) ? -1 : 1;
const startIndex = errorIndex +
(direction === 1
? Math.min(restDelta, hoverDelta)
: Math.max(direction * restDelta, direction * hoverDelta));
const accessibleSwatch = palette.colorContrast(reference, contrastTarget, startIndex, direction);
const accessibleIndex1 = palette.closestIndexOf(accessibleSwatch);
const accessibleIndex2 = accessibleIndex1 + direction * Math.abs(restDelta - hoverDelta);
const indexOneIsRestState = direction === 1
? restDelta < hoverDelta
: direction * restDelta > direction * hoverDelta;
let restIndex;
let hoverIndex;
if (indexOneIsRestState) {
restIndex = accessibleIndex1;
hoverIndex = accessibleIndex2;
}
else {
restIndex = accessibleIndex2;
hoverIndex = accessibleIndex1;
}
return {
rest: palette.get(restIndex),
hover: palette.get(hoverIndex),
active: palette.get(restIndex + direction * activeDelta),
focus: palette.get(restIndex + direction * focusDelta)
};
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/color/recipes/foreground-on-error.js
/**
* @internal
*/
function foregroundOnErrorAlgorithm(reference, contrastTarget) {
return reference.contrast(white) >= contrastTarget ? white : black;
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/design-tokens.js
// Copyright (c) Jupyter Development Team.
// Copyright (c) Microsoft Corporation.
// Distributed under the terms of the Modified BSD License.
const { create: design_tokens_create } = DesignToken;
function createNonCss(name) {
return DesignToken.create({ name, cssCustomPropertyName: null });
}
// General tokens
/** @public */
const bodyFont = design_tokens_create('body-font').withDefault('aktiv-grotesk, "Segoe UI", Arial, Helvetica, sans-serif');
/** @public */
const baseHeightMultiplier = design_tokens_create('base-height-multiplier').withDefault(10);
/** @public */
const baseHorizontalSpacingMultiplier = design_tokens_create('base-horizontal-spacing-multiplier').withDefault(3);
/** @public */
const baseLayerLuminance = design_tokens_create('base-layer-luminance').withDefault(StandardLuminance.DarkMode);
/** @public */
const controlCornerRadius = design_tokens_create('control-corner-radius').withDefault(4);
/** @public */
const density = design_tokens_create('density').withDefault(0);
/** @public */
const designUnit = design_tokens_create('design-unit').withDefault(4);
/**
* Adds to the density on specified element.
*
* @private
*/
const elementScale = design_tokens_create('element-scale').withDefault(0);
/** @public */
const direction = design_tokens_create('direction').withDefault(Direction.ltr);
/** @public */
const disabledOpacity = design_tokens_create('disabled-opacity').withDefault(0.4);
/** @public */
const strokeWidth = design_tokens_create('stroke-width').withDefault(1);
/** @public */
const focusStrokeWidth = design_tokens_create('focus-stroke-width').withDefault(2);
// Typography values
/** @public */
const typeRampBaseFontSize = design_tokens_create('type-ramp-base-font-size').withDefault('14px');
/** @public */
const typeRampBaseLineHeight = design_tokens_create('type-ramp-base-line-height').withDefault('20px');
/** @public */
const typeRampMinus1FontSize = design_tokens_create('type-ramp-minus-1-font-size').withDefault('12px');
/** @public */
const typeRampMinus1LineHeight = design_tokens_create('type-ramp-minus-1-line-height').withDefault('16px');
/** @public */
const typeRampMinus2FontSize = design_tokens_create('type-ramp-minus-2-font-size').withDefault('10px');
/** @public */
const typeRampMinus2LineHeight = design_tokens_create('type-ramp-minus-2-line-height').withDefault('16px');
/** @public */
const typeRampPlus1FontSize = design_tokens_create('type-ramp-plus-1-font-size').withDefault('16px');
/** @public */
const typeRampPlus1LineHeight = design_tokens_create('type-ramp-plus-1-line-height').withDefault('24px');
/** @public */
const typeRampPlus2FontSize = design_tokens_create('type-ramp-plus-2-font-size').withDefault('20px');
/** @public */
const typeRampPlus2LineHeight = design_tokens_create('type-ramp-plus-2-line-height').withDefault('28px');
/** @public */
const typeRampPlus3FontSize = design_tokens_create('type-ramp-plus-3-font-size').withDefault('28px');
/** @public */
const typeRampPlus3LineHeight = design_tokens_create('type-ramp-plus-3-line-height').withDefault('36px');
/** @public */
const typeRampPlus4FontSize = design_tokens_create('type-ramp-plus-4-font-size').withDefault('34px');
/** @public */
const typeRampPlus4LineHeight = design_tokens_create('type-ramp-plus-4-line-height').withDefault('44px');
/** @public */
const typeRampPlus5FontSize = design_tokens_create('type-ramp-plus-5-font-size').withDefault('46px');
/** @public */
const typeRampPlus5LineHeight = design_tokens_create('type-ramp-plus-5-line-height').withDefault('56px');
/** @public */
const typeRampPlus6FontSize = design_tokens_create('type-ramp-plus-6-font-size').withDefault('60px');
/** @public */
const typeRampPlus6LineHeight = design_tokens_create('type-ramp-plus-6-line-height').withDefault('72px');
// Color recipe values
/** @public */
const accentFillRestDelta = createNonCss('accent-fill-rest-delta').withDefault(0);
/** @public */
const accentFillHoverDelta = createNonCss('accent-fill-hover-delta').withDefault(4);
/** @public */
const accentFillActiveDelta = createNonCss('accent-fill-active-delta').withDefault(-5);
/** @public */
const accentFillFocusDelta = createNonCss('accent-fill-focus-delta').withDefault(0);
/** @public */
const accentForegroundRestDelta = createNonCss('accent-foreground-rest-delta').withDefault(0);
/** @public */
const accentForegroundHoverDelta = createNonCss('accent-foreground-hover-delta').withDefault(6);
/** @public */
const accentForegroundActiveDelta = createNonCss('accent-foreground-active-delta').withDefault(-4);
/** @public */
const accentForegroundFocusDelta = createNonCss('accent-foreground-focus-delta').withDefault(0);
/** @public */
const neutralFillRestDelta = createNonCss('neutral-fill-rest-delta').withDefault(7);
/** @public */
const neutralFillHoverDelta = createNonCss('neutral-fill-hover-delta').withDefault(10);
/** @public */
const neutralFillActiveDelta = createNonCss('neutral-fill-active-delta').withDefault(5);
/** @public */
const neutralFillFocusDelta = createNonCss('neutral-fill-focus-delta').withDefault(0);
/** @public */
const neutralFillInputRestDelta = createNonCss('neutral-fill-input-rest-delta').withDefault(0);
/** @public */
const neutralFillInputHoverDelta = createNonCss('neutral-fill-input-hover-delta').withDefault(0);
/** @public */
const neutralFillInputActiveDelta = createNonCss('neutral-fill-input-active-delta').withDefault(0);
/** @public */
const neutralFillInputFocusDelta = createNonCss('neutral-fill-input-focus-delta').withDefault(0);
/** @public */
const neutralFillStealthRestDelta = createNonCss('neutral-fill-stealth-rest-delta').withDefault(0);
/** @public */
const neutralFillStealthHoverDelta = createNonCss('neutral-fill-stealth-hover-delta').withDefault(5);
/** @public */
const neutralFillStealthActiveDelta = createNonCss('neutral-fill-stealth-active-delta').withDefault(3);
/** @public */
const neutralFillStealthFocusDelta = createNonCss('neutral-fill-stealth-focus-delta').withDefault(0);
/** @public */
const neutralFillStrongRestDelta = createNonCss('neutral-fill-strong-rest-delta').withDefault(0);
/** @public */
const neutralFillStrongHoverDelta = createNonCss('neutral-fill-strong-hover-delta').withDefault(8);
/** @public */
const neutralFillStrongActiveDelta = createNonCss('neutral-fill-strong-active-delta').withDefault(-5);
/** @public */
const neutralFillStrongFocusDelta = createNonCss('neutral-fill-strong-focus-delta').withDefault(0);
/** @public */
const neutralFillLayerRestDelta = createNonCss('neutral-fill-layer-rest-delta').withDefault(3);
/** @public */
const neutralStrokeRestDelta = createNonCss('neutral-stroke-rest-delta').withDefault(25);
/** @public */
const neutralStrokeHoverDelta = createNonCss('neutral-stroke-hover-delta').withDefault(40);
/** @public */
const neutralStrokeActiveDelta = createNonCss('neutral-stroke-active-delta').withDefault(16);
/** @public */
const neutralStrokeFocusDelta = createNonCss('neutral-stroke-focus-delta').withDefault(25);
/** @public */
const neutralStrokeDividerRestDelta = createNonCss('neutral-stroke-divider-rest-delta').withDefault(8);
// Color recipes
/** @public */
const neutralColor = design_tokens_create('neutral-color').withDefault(middleGrey);
/** @public */
const neutralPalette = createNonCss('neutral-palette').withDefault((element) => PaletteRGB.from(neutralColor.getValueFor(element)));
/** @public */
const accentColor = design_tokens_create('accent-color').withDefault(accentBase);
/** @public */
const accentPalette = createNonCss('accent-palette').withDefault((element) => PaletteRGB.from(accentColor.getValueFor(element)));
// Neutral Layer Card Container
/** @public */
const neutralLayerCardContainerRecipe = createNonCss('neutral-layer-card-container-recipe').withDefault({
evaluate: (element) => neutralLayerCardContainer(neutralPalette.getValueFor(element), baseLayerLuminance.getValueFor(element), neutralFillLayerRestDelta.getValueFor(element))
});
/** @public */
const design_tokens_neutralLayerCardContainer = design_tokens_create('neutral-layer-card-container').withDefault((element) => neutralLayerCardContainerRecipe.getValueFor(element).evaluate(element));
// Neutral Layer Floating
/** @public */
const neutralLayerFloatingRecipe = createNonCss('neutral-layer-floating-recipe').withDefault({
evaluate: (element) => neutralLayerFloating(neutralPalette.getValueFor(element), baseLayerLuminance.getValueFor(element), neutralFillLayerRestDelta.getValueFor(element))
});
/** @public */
const design_tokens_neutralLayerFloating = design_tokens_create('neutral-layer-floating').withDefault((element) => neutralLayerFloatingRecipe.getValueFor(element).evaluate(element));
// Neutral Layer 1
/** @public */
const neutralLayer1Recipe = createNonCss('neutral-layer-1-recipe').withDefault({
evaluate: (element) => neutralLayer1(neutralPalette.getValueFor(element), baseLayerLuminance.getValueFor(element))
});
/** @public */
const design_tokens_neutralLayer1 = design_tokens_create('neutral-layer-1').withDefault((element) => neutralLayer1Recipe.getValueFor(element).evaluate(element));
// Neutral Layer 2
/** @public */
const neutralLayer2Recipe = createNonCss('neutral-layer-2-recipe').withDefault({
evaluate: (element) => neutralLayer2(neutralPalette.getValueFor(element), baseLayerLuminance.getValueFor(element), neutralFillLayerRestDelta.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element))
});
/** @public */
const design_tokens_neutralLayer2 = design_tokens_create('neutral-layer-2').withDefault((element) => neutralLayer2Recipe.getValueFor(element).evaluate(element));
// Neutral Layer 3
/** @public */
const neutralLayer3Recipe = createNonCss('neutral-layer-3-recipe').withDefault({
evaluate: (element) => neutralLayer3(neutralPalette.getValueFor(element), baseLayerLuminance.getValueFor(element), neutralFillLayerRestDelta.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element))
});
/** @public */
const design_tokens_neutralLayer3 = design_tokens_create('neutral-layer-3').withDefault((element) => neutralLayer3Recipe.getValueFor(element).evaluate(element));
// Neutral Layer 4
/** @public */
const neutralLayer4Recipe = createNonCss('neutral-layer-4-recipe').withDefault({
evaluate: (element) => neutralLayer4(neutralPalette.getValueFor(element), baseLayerLuminance.getValueFor(element), neutralFillLayerRestDelta.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element))
});
/** @public */
const design_tokens_neutralLayer4 = design_tokens_create('neutral-layer-4').withDefault((element) => neutralLayer4Recipe.getValueFor(element).evaluate(element));
/** @public */
const fillColor = design_tokens_create('fill-color').withDefault(element => design_tokens_neutralLayer1.getValueFor(element));
var ContrastTarget;
(function (ContrastTarget) {
ContrastTarget[ContrastTarget["normal"] = 4.5] = "normal";
ContrastTarget[ContrastTarget["large"] = 7] = "large";
})(ContrastTarget || (ContrastTarget = {}));
// Accent Fill
/** @public */
const accentFillRecipe = design_tokens_create({
name: 'accent-fill-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => accentFill(accentPalette.getValueFor(element), neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), accentFillHoverDelta.getValueFor(element), accentFillActiveDelta.getValueFor(element), accentFillFocusDelta.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element))
});
/** @public */
const accentFillRest = design_tokens_create('accent-fill-rest').withDefault((element) => {
return accentFillRecipe.getValueFor(element).evaluate(element).rest;
});
/** @public */
const accentFillHover = design_tokens_create('accent-fill-hover').withDefault((element) => {
return accentFillRecipe.getValueFor(element).evaluate(element).hover;
});
/** @public */
const accentFillActive = design_tokens_create('accent-fill-active').withDefault((element) => {
return accentFillRecipe.getValueFor(element).evaluate(element).active;
});
/** @public */
const accentFillFocus = design_tokens_create('accent-fill-focus').withDefault((element) => {
return accentFillRecipe.getValueFor(element).evaluate(element).focus;
});
// Foreground On Accent
const foregroundOnAccentByContrast = (contrast) => (element, reference) => {
return foregroundOnAccent(reference || accentFillRest.getValueFor(element), contrast);
};
/** @public */
const foregroundOnAccentRecipe = createNonCss('foreground-on-accent-recipe').withDefault({
evaluate: (element, reference) => foregroundOnAccentByContrast(ContrastTarget.normal)(element, reference)
});
/** @public */
const foregroundOnAccentRest = design_tokens_create('foreground-on-accent-rest').withDefault((element) => foregroundOnAccentRecipe
.getValueFor(element)
.evaluate(element, accentFillRest.getValueFor(element)));
/** @public */
const foregroundOnAccentHover = design_tokens_create('foreground-on-accent-hover').withDefault((element) => foregroundOnAccentRecipe
.getValueFor(element)
.evaluate(element, accentFillHover.getValueFor(element)));
/** @public */
const foregroundOnAccentActive = design_tokens_create('foreground-on-accent-active').withDefault((element) => foregroundOnAccentRecipe
.getValueFor(element)
.evaluate(element, accentFillActive.getValueFor(element)));
/** @public */
const foregroundOnAccentFocus = design_tokens_create('foreground-on-accent-focus').withDefault((element) => foregroundOnAccentRecipe
.getValueFor(element)
.evaluate(element, accentFillFocus.getValueFor(element)));
/** @public */
const foregroundOnAccentLargeRecipe = createNonCss('foreground-on-accent-large-recipe').withDefault({
evaluate: (element, reference) => foregroundOnAccentByContrast(ContrastTarget.large)(element, reference)
});
/** @public */
const foregroundOnAccentRestLarge = design_tokens_create('foreground-on-accent-rest-large').withDefault((element) => foregroundOnAccentLargeRecipe
.getValueFor(element)
.evaluate(element, accentFillRest.getValueFor(element)));
/** @public */
const foregroundOnAccentHoverLarge = design_tokens_create('foreground-on-accent-hover-large').withDefault((element) => foregroundOnAccentLargeRecipe
.getValueFor(element)
.evaluate(element, accentFillHover.getValueFor(element)));
/** @public */
const foregroundOnAccentActiveLarge = design_tokens_create('foreground-on-accent-active-large').withDefault((element) => foregroundOnAccentLargeRecipe
.getValueFor(element)
.evaluate(element, accentFillActive.getValueFor(element)));
/** @public */
const foregroundOnAccentFocusLarge = design_tokens_create('foreground-on-accent-focus-large').withDefault((element) => foregroundOnAccentLargeRecipe
.getValueFor(element)
.evaluate(element, accentFillFocus.getValueFor(element)));
// Accent Foreground
const accentForegroundByContrast = (contrast) => (element, reference) => accentForeground(accentPalette.getValueFor(element), reference || fillColor.getValueFor(element), contrast, accentForegroundRestDelta.getValueFor(element), accentForegroundHoverDelta.getValueFor(element), accentForegroundActiveDelta.getValueFor(element), accentForegroundFocusDelta.getValueFor(element));
/** @public */
const accentForegroundRecipe = design_tokens_create({
name: 'accent-foreground-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => accentForegroundByContrast(ContrastTarget.normal)(element, reference)
});
/** @public */
const accentForegroundRest = design_tokens_create('accent-foreground-rest').withDefault((element) => accentForegroundRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const accentForegroundHover = design_tokens_create('accent-foreground-hover').withDefault((element) => accentForegroundRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const accentForegroundActive = design_tokens_create('accent-foreground-active').withDefault((element) => accentForegroundRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const accentForegroundFocus = design_tokens_create('accent-foreground-focus').withDefault((element) => accentForegroundRecipe.getValueFor(element).evaluate(element).focus);
// Neutral Fill
/** @public */
const neutralFillRecipe = design_tokens_create({
name: 'neutral-fill-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => neutralFill(neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element), neutralFillFocusDelta.getValueFor(element))
});
/** @public */
const neutralFillRest = design_tokens_create('neutral-fill-rest').withDefault((element) => neutralFillRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const neutralFillHover = design_tokens_create('neutral-fill-hover').withDefault((element) => neutralFillRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const neutralFillActive = design_tokens_create('neutral-fill-active').withDefault((element) => neutralFillRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const neutralFillFocus = design_tokens_create('neutral-fill-focus').withDefault((element) => neutralFillRecipe.getValueFor(element).evaluate(element).focus);
// Neutral Fill Input
/** @public */
const neutralFillInputRecipe = design_tokens_create({
name: 'neutral-fill-input-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => neutralFillInput(neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillInputRestDelta.getValueFor(element), neutralFillInputHoverDelta.getValueFor(element), neutralFillInputActiveDelta.getValueFor(element), neutralFillInputFocusDelta.getValueFor(element))
});
/** @public */
const neutralFillInputRest = design_tokens_create('neutral-fill-input-rest').withDefault((element) => neutralFillInputRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const neutralFillInputHover = design_tokens_create('neutral-fill-input-hover').withDefault((element) => neutralFillInputRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const neutralFillInputActive = design_tokens_create('neutral-fill-input-active').withDefault((element) => neutralFillInputRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const neutralFillInputFocus = design_tokens_create('neutral-fill-input-focus').withDefault((element) => neutralFillInputRecipe.getValueFor(element).evaluate(element).focus);
// Neutral Fill Stealth
/** @public */
const neutralFillStealthRecipe = design_tokens_create({
name: 'neutral-fill-stealth-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => neutralFillStealth(neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillStealthRestDelta.getValueFor(element), neutralFillStealthHoverDelta.getValueFor(element), neutralFillStealthActiveDelta.getValueFor(element), neutralFillStealthFocusDelta.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element), neutralFillFocusDelta.getValueFor(element))
});
/** @public */
const neutralFillStealthRest = design_tokens_create('neutral-fill-stealth-rest').withDefault((element) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const neutralFillStealthHover = design_tokens_create('neutral-fill-stealth-hover').withDefault((element) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const neutralFillStealthActive = design_tokens_create('neutral-fill-stealth-active').withDefault((element) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const neutralFillStealthFocus = design_tokens_create('neutral-fill-stealth-focus').withDefault((element) => neutralFillStealthRecipe.getValueFor(element).evaluate(element).focus);
// Neutral Fill Strong
/** @public */
const neutralFillStrongRecipe = design_tokens_create({
name: 'neutral-fill-strong-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => neutralFillContrast(neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillStrongRestDelta.getValueFor(element), neutralFillStrongHoverDelta.getValueFor(element), neutralFillStrongActiveDelta.getValueFor(element), neutralFillStrongFocusDelta.getValueFor(element))
});
/** @public */
const neutralFillStrongRest = design_tokens_create('neutral-fill-strong-rest').withDefault((element) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const neutralFillStrongHover = design_tokens_create('neutral-fill-strong-hover').withDefault((element) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const neutralFillStrongActive = design_tokens_create('neutral-fill-strong-active').withDefault((element) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const neutralFillStrongFocus = design_tokens_create('neutral-fill-strong-focus').withDefault((element) => neutralFillStrongRecipe.getValueFor(element).evaluate(element).focus);
// Neutral Fill Layer
/** @public */
const neutralFillLayerRecipe = createNonCss('neutral-fill-layer-recipe').withDefault({
evaluate: (element, reference) => neutralFillLayer(neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralFillLayerRestDelta.getValueFor(element))
});
/** @public */
const neutralFillLayerRest = design_tokens_create('neutral-fill-layer-rest').withDefault((element) => neutralFillLayerRecipe.getValueFor(element).evaluate(element));
// Focus Stroke Outer
/** @public */
const focusStrokeOuterRecipe = createNonCss('focus-stroke-outer-recipe').withDefault({
evaluate: (element) => focusStrokeOuter(neutralPalette.getValueFor(element), fillColor.getValueFor(element))
});
/** @public */
const design_tokens_focusStrokeOuter = design_tokens_create('focus-stroke-outer').withDefault((element) => focusStrokeOuterRecipe.getValueFor(element).evaluate(element));
// Focus Stroke Inner
/** @public */
const focusStrokeInnerRecipe = createNonCss('focus-stroke-inner-recipe').withDefault({
evaluate: (element) => focusStrokeInner(accentPalette.getValueFor(element), fillColor.getValueFor(element), design_tokens_focusStrokeOuter.getValueFor(element))
});
/** @public */
const design_tokens_focusStrokeInner = design_tokens_create('focus-stroke-inner').withDefault((element) => focusStrokeInnerRecipe.getValueFor(element).evaluate(element));
// Neutral Foreground Hint
/** @public */
const neutralForegroundHintRecipe = createNonCss('neutral-foreground-hint-recipe').withDefault({
evaluate: (element) => neutralForegroundHint(neutralPalette.getValueFor(element), fillColor.getValueFor(element))
});
/** @public */
const design_tokens_neutralForegroundHint = design_tokens_create('neutral-foreground-hint').withDefault((element) => neutralForegroundHintRecipe.getValueFor(element).evaluate(element));
// Neutral Foreground
/** @public */
const neutralForegroundRecipe = createNonCss('neutral-foreground-recipe').withDefault({
evaluate: (element) => neutralForeground(neutralPalette.getValueFor(element), fillColor.getValueFor(element))
});
/** @public */
const neutralForegroundRest = design_tokens_create('neutral-foreground-rest').withDefault((element) => neutralForegroundRecipe.getValueFor(element).evaluate(element));
// Neutral Stroke
/** @public */
const neutralStrokeRecipe = design_tokens_create({
name: 'neutral-stroke-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element) => {
return neutralStroke(neutralPalette.getValueFor(element), fillColor.getValueFor(element), neutralStrokeRestDelta.getValueFor(element), neutralStrokeHoverDelta.getValueFor(element), neutralStrokeActiveDelta.getValueFor(element), neutralStrokeFocusDelta.getValueFor(element));
}
});
/** @public */
const neutralStrokeRest = design_tokens_create('neutral-stroke-rest').withDefault((element) => neutralStrokeRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const neutralStrokeHover = design_tokens_create('neutral-stroke-hover').withDefault((element) => neutralStrokeRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const neutralStrokeActive = design_tokens_create('neutral-stroke-active').withDefault((element) => neutralStrokeRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const neutralStrokeFocus = design_tokens_create('neutral-stroke-focus').withDefault((element) => neutralStrokeRecipe.getValueFor(element).evaluate(element).focus);
// Neutral Stroke Divider
/** @public */
const neutralStrokeDividerRecipe = createNonCss('neutral-stroke-divider-recipe').withDefault({
evaluate: (element, reference) => neutralStrokeDivider(neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), neutralStrokeDividerRestDelta.getValueFor(element))
});
/** @public */
const neutralStrokeDividerRest = design_tokens_create('neutral-stroke-divider-rest').withDefault(element => neutralStrokeDividerRecipe.getValueFor(element).evaluate(element));
/**
* The control height formula expressed as a design token.
* This token does not provide a CSS custom property.
*
* @public
*/
const heightNumberAsToken = DesignToken.create({
name: 'height-number',
cssCustomPropertyName: null
}).withDefault(target => (baseHeightMultiplier.getValueFor(target) + density.getValueFor(target)) *
designUnit.getValueFor(target));
/*
* The error palette is built using the same color algorithm as the accent palette
* But by copying the algorithm from @microsoft/fast-components at commit 03d711f222bd816834a5e1d60256d3e083b27c27
* as some helpers are not exported.
* The delta used are those of the accent palette.
*/
/** @public */
const errorColor = design_tokens_create('error-color').withDefault(errorBase);
/**
* Error palette
* @public
*/
const errorPalette = createNonCss('error-palette').withDefault((element) => PaletteRGB.from(errorColor.getValueFor(element)));
// Error Fill
/** @public */
const errorFillRecipe = design_tokens_create({
name: 'error-fill-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => errorFillAlgorithm(errorPalette.getValueFor(element), neutralPalette.getValueFor(element), reference || fillColor.getValueFor(element), accentFillHoverDelta.getValueFor(element), accentFillActiveDelta.getValueFor(element), accentFillFocusDelta.getValueFor(element), neutralFillRestDelta.getValueFor(element), neutralFillHoverDelta.getValueFor(element), neutralFillActiveDelta.getValueFor(element))
});
/** @public */
const errorFillRest = design_tokens_create('error-fill-rest').withDefault((element) => {
return errorFillRecipe.getValueFor(element).evaluate(element).rest;
});
/** @public */
const errorFillHover = design_tokens_create('error-fill-hover').withDefault((element) => {
return errorFillRecipe.getValueFor(element).evaluate(element).hover;
});
/** @public */
const errorFillActive = design_tokens_create('error-fill-active').withDefault((element) => {
return errorFillRecipe.getValueFor(element).evaluate(element).active;
});
/** @public */
const errorFillFocus = design_tokens_create('error-fill-focus').withDefault((element) => {
return errorFillRecipe.getValueFor(element).evaluate(element).focus;
});
// Foreground On Error
const foregroundOnErrorByContrast = (contrast) => (element, reference) => {
return foregroundOnErrorAlgorithm(reference || errorFillRest.getValueFor(element), contrast);
};
/** @public */
const foregroundOnErrorRecipe = design_tokens_create({
name: 'foreground-on-error-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => foregroundOnErrorByContrast(ContrastTarget.normal)(element, reference)
});
/** @public */
const foregroundOnErrorRest = design_tokens_create('foreground-on-error-rest').withDefault((element) => foregroundOnErrorRecipe
.getValueFor(element)
.evaluate(element, errorFillRest.getValueFor(element)));
/** @public */
const foregroundOnErrorHover = design_tokens_create('foreground-on-error-hover').withDefault((element) => foregroundOnErrorRecipe
.getValueFor(element)
.evaluate(element, errorFillHover.getValueFor(element)));
/** @public */
const foregroundOnErrorActive = design_tokens_create('foreground-on-error-active').withDefault((element) => foregroundOnErrorRecipe
.getValueFor(element)
.evaluate(element, errorFillActive.getValueFor(element)));
/** @public */
const foregroundOnErrorFocus = design_tokens_create('foreground-on-error-focus').withDefault((element) => foregroundOnErrorRecipe
.getValueFor(element)
.evaluate(element, errorFillFocus.getValueFor(element)));
/** @public */
const foregroundOnErrorLargeRecipe = design_tokens_create({
name: 'foreground-on-error-large-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => foregroundOnErrorByContrast(ContrastTarget.large)(element, reference)
});
/** @public */
const foregroundOnErrorRestLarge = design_tokens_create('foreground-on-error-rest-large').withDefault((element) => foregroundOnErrorLargeRecipe
.getValueFor(element)
.evaluate(element, errorFillRest.getValueFor(element)));
/** @public */
const foregroundOnErrorHoverLarge = design_tokens_create('foreground-on-error-hover-large').withDefault((element) => foregroundOnErrorLargeRecipe
.getValueFor(element)
.evaluate(element, errorFillHover.getValueFor(element)));
/** @public */
const foregroundOnErrorActiveLarge = design_tokens_create('foreground-on-error-active-large').withDefault((element) => foregroundOnErrorLargeRecipe
.getValueFor(element)
.evaluate(element, errorFillActive.getValueFor(element)));
/** @public */
const foregroundOnErrorFocusLarge = design_tokens_create('foreground-on-error-focus-large').withDefault((element) => foregroundOnErrorLargeRecipe
.getValueFor(element)
.evaluate(element, errorFillFocus.getValueFor(element)));
// Error Foreground
const errorForegroundByContrast = (contrast) => (element, reference) => errorForegroundAlgorithm(errorPalette.getValueFor(element), reference || fillColor.getValueFor(element), contrast, accentForegroundRestDelta.getValueFor(element), accentForegroundHoverDelta.getValueFor(element), accentForegroundActiveDelta.getValueFor(element), accentForegroundFocusDelta.getValueFor(element));
/** @public */
const errorForegroundRecipe = design_tokens_create({
name: 'error-foreground-recipe',
cssCustomPropertyName: null
}).withDefault({
evaluate: (element, reference) => errorForegroundByContrast(ContrastTarget.normal)(element, reference)
});
/** @public */
const errorForegroundRest = design_tokens_create('error-foreground-rest').withDefault((element) => errorForegroundRecipe.getValueFor(element).evaluate(element).rest);
/** @public */
const errorForegroundHover = design_tokens_create('error-foreground-hover').withDefault((element) => errorForegroundRecipe.getValueFor(element).evaluate(element).hover);
/** @public */
const errorForegroundActive = design_tokens_create('error-foreground-active').withDefault((element) => errorForegroundRecipe.getValueFor(element).evaluate(element).active);
/** @public */
const errorForegroundFocus = design_tokens_create('error-foreground-focus').withDefault((element) => errorForegroundRecipe.getValueFor(element).evaluate(element).focus);
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/utilities/theme/applyTheme.js
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
const THEME_NAME_BODY_ATTRIBUTE = 'data-jp-theme-name';
const THEME_MODE_BODY_ATTRIBUTE = 'data-jp-theme-light';
// Use to determine the neutral color and possibly if theme is dark
const BASE_LAYOUT_COLOR = '--jp-layout-color1';
/**
* Flag to initialized only one listener
*/
let isThemeChangeInitialized = false;
/**
* Configures a MutationObserver to watch for Jupyter theme changes and
* applies the current Jupyter theme to the toolkit components.
*/
function addJupyterLabThemeChangeListener() {
if (!isThemeChangeInitialized) {
isThemeChangeInitialized = true;
initThemeChangeListener();
}
}
function initThemeChangeListener() {
const addObserver = () => {
const observer = new MutationObserver(() => {
applyJupyterTheme();
});
observer.observe(document.body, {
attributes: true,
attributeFilter: [THEME_NAME_BODY_ATTRIBUTE],
childList: false,
characterData: false
});
applyJupyterTheme();
};
if (document.readyState === 'complete') {
addObserver();
}
else {
window.addEventListener('load', addObserver);
}
}
/**
* Convert a string to an integer.
*
* @param value String to convert
* @returns Extracted integer or null
*/
const intConverter = (value) => {
const parsedValue = parseInt(value, 10);
return isNaN(parsedValue) ? null : parsedValue;
};
/**
* Mapping JupyterLab CSS variables to FAST design tokens
*/
const tokenMappings = {
'--jp-border-width': {
converter: intConverter,
token: strokeWidth
},
'--jp-border-radius': {
converter: intConverter,
token: controlCornerRadius
},
[BASE_LAYOUT_COLOR]: {
converter: (value, isDark) => {
const parsedColor = parseColor(value);
if (parsedColor) {
const hsl = color_converters_rgbToHSL(parsedColor);
// Neutral luminance should be about 50%
const correctedHSL = color_hsl_ColorHSL.fromObject({
h: hsl.h,
s: hsl.s,
l: 0.5
});
const correctedRGB = color_converters_hslToRGB(correctedHSL);
return SwatchRGB.create(correctedRGB.r, correctedRGB.g, correctedRGB.b);
}
else {
return null;
}
},
token: neutralColor
},
'--jp-brand-color1': {
converter: (value, isDark) => {
const parsedColor = parseColor(value);
if (parsedColor) {
const hsl = color_converters_rgbToHSL(parsedColor);
// Correct luminance to get accent fill closer to brand color 1
const direction = isDark ? 1 : -1;
const correctedHSL = color_hsl_ColorHSL.fromObject({
h: hsl.h,
s: hsl.s,
l: hsl.l +
(direction * accentFillHoverDelta.getValueFor(document.body)) / 94.0
});
const correctedRGB = color_converters_hslToRGB(correctedHSL);
return SwatchRGB.create(correctedRGB.r, correctedRGB.g, correctedRGB.b);
}
else {
return null;
}
},
token: accentColor
},
'--jp-error-color1': {
converter: (value, isDark) => {
const parsedColor = parseColor(value);
if (parsedColor) {
const hsl = color_converters_rgbToHSL(parsedColor);
// Correct luminance to get error fill closer
const direction = isDark ? 1 : -1;
const correctedHSL = color_hsl_ColorHSL.fromObject({
h: hsl.h,
s: hsl.s,
l: hsl.l +
(direction * accentFillHoverDelta.getValueFor(document.body)) / 94.0
});
const correctedRGB = color_converters_hslToRGB(correctedHSL);
return SwatchRGB.create(correctedRGB.r, correctedRGB.g, correctedRGB.b);
}
else {
return null;
}
},
token: errorColor
},
'--jp-ui-font-family': {
token: bodyFont
},
'--jp-ui-font-size1': {
token: typeRampBaseFontSize
}
};
/**
* Applies the current Jupyter theme to the toolkit components.
*/
function applyJupyterTheme() {
var _a;
// Get all the styles applied to the
tag in the webview HTML
// Importantly this includes all the CSS variables associated with the
// current Jupyter theme
const styles = getComputedStyle(document.body);
// Set mode
// It will look at the body attribute or try to extrapolate
const themeMode = document.body.getAttribute(THEME_MODE_BODY_ATTRIBUTE);
let isDark_ = false;
if (themeMode) {
isDark_ = themeMode === 'false';
}
else {
const layoutColor = styles.getPropertyValue(BASE_LAYOUT_COLOR).toString();
if (layoutColor) {
const parsedColor = parseColor(layoutColor);
if (parsedColor) {
isDark_ = isDark(SwatchRGB.create(parsedColor.r, parsedColor.g, parsedColor.b));
console.debug(`Theme is ${isDark_ ? 'dark' : 'light'} based on '${BASE_LAYOUT_COLOR}' value: ${layoutColor}.`);
}
}
}
baseLayerLuminance.setValueFor(document.body, isDark_ ? StandardLuminance.DarkMode : StandardLuminance.LightMode);
for (const jpTokenName in tokenMappings) {
const toolkitTokenName = tokenMappings[jpTokenName];
const value = styles.getPropertyValue(jpTokenName).toString();
if (document.body && value !== '') {
const parsedValue = ((_a = toolkitTokenName.converter) !== null && _a !== void 0 ? _a : ((v) => v))(value.trim(), isDark_);
if (parsedValue !== null) {
toolkitTokenName.token.setValueFor(document.body, parsedValue);
}
else {
console.error(`Fail to parse value '${value}' for '${jpTokenName}' as FAST design token.`);
}
}
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-web-utilities/dist/key-codes.js
/**
* Key Code values
* @deprecated - KeyCodes are deprecated, use individual string key exports
*/
var KeyCodes;
(function (KeyCodes) {
KeyCodes[KeyCodes["alt"] = 18] = "alt";
KeyCodes[KeyCodes["arrowDown"] = 40] = "arrowDown";
KeyCodes[KeyCodes["arrowLeft"] = 37] = "arrowLeft";
KeyCodes[KeyCodes["arrowRight"] = 39] = "arrowRight";
KeyCodes[KeyCodes["arrowUp"] = 38] = "arrowUp";
KeyCodes[KeyCodes["back"] = 8] = "back";
KeyCodes[KeyCodes["backSlash"] = 220] = "backSlash";
KeyCodes[KeyCodes["break"] = 19] = "break";
KeyCodes[KeyCodes["capsLock"] = 20] = "capsLock";
KeyCodes[KeyCodes["closeBracket"] = 221] = "closeBracket";
KeyCodes[KeyCodes["colon"] = 186] = "colon";
KeyCodes[KeyCodes["colon2"] = 59] = "colon2";
KeyCodes[KeyCodes["comma"] = 188] = "comma";
KeyCodes[KeyCodes["ctrl"] = 17] = "ctrl";
KeyCodes[KeyCodes["delete"] = 46] = "delete";
KeyCodes[KeyCodes["end"] = 35] = "end";
KeyCodes[KeyCodes["enter"] = 13] = "enter";
KeyCodes[KeyCodes["equals"] = 187] = "equals";
KeyCodes[KeyCodes["equals2"] = 61] = "equals2";
KeyCodes[KeyCodes["equals3"] = 107] = "equals3";
KeyCodes[KeyCodes["escape"] = 27] = "escape";
KeyCodes[KeyCodes["forwardSlash"] = 191] = "forwardSlash";
KeyCodes[KeyCodes["function1"] = 112] = "function1";
KeyCodes[KeyCodes["function10"] = 121] = "function10";
KeyCodes[KeyCodes["function11"] = 122] = "function11";
KeyCodes[KeyCodes["function12"] = 123] = "function12";
KeyCodes[KeyCodes["function2"] = 113] = "function2";
KeyCodes[KeyCodes["function3"] = 114] = "function3";
KeyCodes[KeyCodes["function4"] = 115] = "function4";
KeyCodes[KeyCodes["function5"] = 116] = "function5";
KeyCodes[KeyCodes["function6"] = 117] = "function6";
KeyCodes[KeyCodes["function7"] = 118] = "function7";
KeyCodes[KeyCodes["function8"] = 119] = "function8";
KeyCodes[KeyCodes["function9"] = 120] = "function9";
KeyCodes[KeyCodes["home"] = 36] = "home";
KeyCodes[KeyCodes["insert"] = 45] = "insert";
KeyCodes[KeyCodes["menu"] = 93] = "menu";
KeyCodes[KeyCodes["minus"] = 189] = "minus";
KeyCodes[KeyCodes["minus2"] = 109] = "minus2";
KeyCodes[KeyCodes["numLock"] = 144] = "numLock";
KeyCodes[KeyCodes["numPad0"] = 96] = "numPad0";
KeyCodes[KeyCodes["numPad1"] = 97] = "numPad1";
KeyCodes[KeyCodes["numPad2"] = 98] = "numPad2";
KeyCodes[KeyCodes["numPad3"] = 99] = "numPad3";
KeyCodes[KeyCodes["numPad4"] = 100] = "numPad4";
KeyCodes[KeyCodes["numPad5"] = 101] = "numPad5";
KeyCodes[KeyCodes["numPad6"] = 102] = "numPad6";
KeyCodes[KeyCodes["numPad7"] = 103] = "numPad7";
KeyCodes[KeyCodes["numPad8"] = 104] = "numPad8";
KeyCodes[KeyCodes["numPad9"] = 105] = "numPad9";
KeyCodes[KeyCodes["numPadDivide"] = 111] = "numPadDivide";
KeyCodes[KeyCodes["numPadDot"] = 110] = "numPadDot";
KeyCodes[KeyCodes["numPadMinus"] = 109] = "numPadMinus";
KeyCodes[KeyCodes["numPadMultiply"] = 106] = "numPadMultiply";
KeyCodes[KeyCodes["numPadPlus"] = 107] = "numPadPlus";
KeyCodes[KeyCodes["openBracket"] = 219] = "openBracket";
KeyCodes[KeyCodes["pageDown"] = 34] = "pageDown";
KeyCodes[KeyCodes["pageUp"] = 33] = "pageUp";
KeyCodes[KeyCodes["period"] = 190] = "period";
KeyCodes[KeyCodes["print"] = 44] = "print";
KeyCodes[KeyCodes["quote"] = 222] = "quote";
KeyCodes[KeyCodes["scrollLock"] = 145] = "scrollLock";
KeyCodes[KeyCodes["shift"] = 16] = "shift";
KeyCodes[KeyCodes["space"] = 32] = "space";
KeyCodes[KeyCodes["tab"] = 9] = "tab";
KeyCodes[KeyCodes["tilde"] = 192] = "tilde";
KeyCodes[KeyCodes["windowsLeft"] = 91] = "windowsLeft";
KeyCodes[KeyCodes["windowsOpera"] = 219] = "windowsOpera";
KeyCodes[KeyCodes["windowsRight"] = 92] = "windowsRight";
})(KeyCodes || (KeyCodes = {}));
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeAlt = 18;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeArrowDown = 40;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeArrowLeft = 37;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeArrowRight = 39;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeArrowUp = 38;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeBack = 8;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeBackSlash = 220;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeBreak = 19;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeCapsLock = 20;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeCloseBracket = 221;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeColon = 186;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeColon2 = 59; // Opera and Firefox
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeComma = 188;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeCtrl = 17;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeDelete = 46;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeEnd = 35;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeEnter = 13;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeEquals = 187;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeEquals2 = 61; // Opera
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeEquals3 = 107; // Firefox
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeEscape = 27;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeForwardSlash = 191;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction1 = 112;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction10 = 121;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction11 = 122;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction12 = 123;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction2 = 113;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction3 = 114;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction4 = 115;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction5 = 116;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction6 = 117;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction7 = 118;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction8 = 119;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeFunction9 = 120;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeHome = 36;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeInsert = 45;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeMenu = 93;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeMinus = 189;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeMinus2 = 109; // Opera and Firefox
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumLock = 144;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad0 = 96;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad1 = 97;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad2 = 98;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad3 = 99;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad4 = 100;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad5 = 101;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad6 = 102;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad7 = 103;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad8 = 104;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPad9 = 105;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPadDivide = 111;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPadDot = 110;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPadMinus = 109;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPadMultiply = 106;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeNumPadPlus = 107;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeOpenBracket = 219;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodePageDown = 34;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodePageUp = 33;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodePeriod = 190;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodePrint = 44;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeQuote = 222;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeScrollLock = 145;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeShift = 16;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeSpace = 32;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeTab = 9;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeTilde = 192;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeWindowsLeft = 91;
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeWindowsOpera = 219; // Opera
/**
* @deprecated - KeyCodes are deprecated, use string key exports
*/
const keyCodeWindowsRight = 92;
/**
* String values for use with KeyboardEvent.key
*/
const keyArrowDown = "ArrowDown";
const keyArrowLeft = "ArrowLeft";
const keyArrowRight = "ArrowRight";
const keyArrowUp = "ArrowUp";
const keyEnter = "Enter";
const keyEscape = "Escape";
const keyHome = "Home";
const keyEnd = "End";
const keyFunction2 = "F2";
const keyPageDown = "PageDown";
const keyPageUp = "PageUp";
const keySpace = " ";
const keyTab = "Tab";
const keyBackspace = "Backspace";
const keyDelete = "Delete";
const ArrowKeys = {
ArrowDown: keyArrowDown,
ArrowLeft: keyArrowLeft,
ArrowRight: keyArrowRight,
ArrowUp: keyArrowUp,
};
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-web-utilities/dist/numbers.js
/**
* This method keeps a given value within the bounds of a min and max value. If the value
* is larger than the max, the minimum value will be returned. If the value is smaller than the minimum,
* the maximum will be returned. Otherwise, the value is returned un-changed.
*/
function wrapInBounds(min, max, value) {
if (value < min) {
return max;
}
else if (value > max) {
return min;
}
return value;
}
/**
* Ensures that a value is between a min and max value. If value is lower than min, min will be returned.
* If value is greater than max, max will be returned.
*/
function limit(min, max, value) {
return Math.min(Math.max(value, min), max);
}
/**
* Determines if a number value is within a specified range.
*
* @param value - the value to check
* @param min - the range start
* @param max - the range end
*/
function inRange(value, min, max = 0) {
[min, max] = [min, max].sort((a, b) => a - b);
return min <= value && value < max;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/di/di.js
/**
* Big thanks to https://github.com/fkleuver and the https://github.com/aurelia/aurelia project
* for the bulk of this code and many of the associated tests.
*/
// Tiny polyfill for TypeScript's Reflect metadata API.
const metadataByTarget = new Map();
if (!("metadata" in Reflect)) {
Reflect.metadata = function (key, value) {
return function (target) {
Reflect.defineMetadata(key, value, target);
};
};
Reflect.defineMetadata = function (key, value, target) {
let metadata = metadataByTarget.get(target);
if (metadata === void 0) {
metadataByTarget.set(target, (metadata = new Map()));
}
metadata.set(key, value);
};
Reflect.getOwnMetadata = function (key, target) {
const metadata = metadataByTarget.get(target);
if (metadata !== void 0) {
return metadata.get(key);
}
return void 0;
};
}
/**
* A utility class used that constructs and registers resolvers for a dependency
* injection container. Supports a standard set of object lifetimes.
* @public
*/
class ResolverBuilder {
/**
*
* @param container - The container to create resolvers for.
* @param key - The key to register resolvers under.
*/
constructor(container, key) {
this.container = container;
this.key = key;
}
/**
* Creates a resolver for an existing object instance.
* @param value - The instance to resolve.
* @returns The resolver.
*/
instance(value) {
return this.registerResolver(0 /* instance */, value);
}
/**
* Creates a resolver that enforces a singleton lifetime.
* @param value - The type to create and cache the singleton for.
* @returns The resolver.
*/
singleton(value) {
return this.registerResolver(1 /* singleton */, value);
}
/**
* Creates a resolver that creates a new instance for every dependency request.
* @param value - The type to create instances of.
* @returns - The resolver.
*/
transient(value) {
return this.registerResolver(2 /* transient */, value);
}
/**
* Creates a resolver that invokes a callback function for every dependency resolution
* request, allowing custom logic to return the dependency.
* @param value - The callback to call during resolution.
* @returns The resolver.
*/
callback(value) {
return this.registerResolver(3 /* callback */, value);
}
/**
* Creates a resolver that invokes a callback function the first time that a dependency
* resolution is requested. The returned value is then cached and provided for all
* subsequent requests.
* @param value - The callback to call during the first resolution.
* @returns The resolver.
*/
cachedCallback(value) {
return this.registerResolver(3 /* callback */, cacheCallbackResult(value));
}
/**
* Aliases the current key to a different key.
* @param destinationKey - The key to point the alias to.
* @returns The resolver.
*/
aliasTo(destinationKey) {
return this.registerResolver(5 /* alias */, destinationKey);
}
registerResolver(strategy, state) {
const { container, key } = this;
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
this.container = this.key = (void 0);
return container.registerResolver(key, new ResolverImpl(key, strategy, state));
}
}
function cloneArrayWithPossibleProps(source) {
const clone = source.slice();
const keys = Object.keys(source);
const len = keys.length;
let key;
for (let i = 0; i < len; ++i) {
key = keys[i];
if (!isArrayIndex(key)) {
clone[key] = source[key];
}
}
return clone;
}
/**
* A set of default resolvers useful in configuring a container.
* @public
*/
const DefaultResolver = Object.freeze({
/**
* Disables auto-registration and throws for all un-registered dependencies.
* @param key - The key to create the resolver for.
*/
none(key) {
throw Error(`${key.toString()} not registered, did you forget to add @singleton()?`);
},
/**
* Provides default singleton resolution behavior during auto-registration.
* @param key - The key to create the resolver for.
* @returns The resolver.
*/
singleton(key) {
return new ResolverImpl(key, 1 /* singleton */, key);
},
/**
* Provides default transient resolution behavior during auto-registration.
* @param key - The key to create the resolver for.
* @returns The resolver.
*/
transient(key) {
return new ResolverImpl(key, 2 /* transient */, key);
},
});
/**
* Configuration for a dependency injection container.
* @public
*/
const ContainerConfiguration = Object.freeze({
/**
* The default configuration used when creating a DOM-disconnected container.
* @remarks
* The default creates a root container, with no parent container. It does not handle
* owner requests and it uses singleton resolution behavior for auto-registration.
*/
default: Object.freeze({
parentLocator: () => null,
responsibleForOwnerRequests: false,
defaultResolver: DefaultResolver.singleton,
}),
});
const dependencyLookup = new Map();
function getParamTypes(key) {
return (Type) => {
return Reflect.getOwnMetadata(key, Type);
};
}
let rootDOMContainer = null;
/**
* The gateway to dependency injection APIs.
* @public
*/
const DI = Object.freeze({
/**
* Creates a new dependency injection container.
* @param config - The configuration for the container.
* @returns A newly created dependency injection container.
*/
createContainer(config) {
return new ContainerImpl(null, Object.assign({}, ContainerConfiguration.default, config));
},
/**
* Finds the dependency injection container responsible for providing dependencies
* to the specified node.
* @param node - The node to find the responsible container for.
* @returns The container responsible for providing dependencies to the node.
* @remarks
* This will be the same as the parent container if the specified node
* does not itself host a container configured with responsibleForOwnerRequests.
*/
findResponsibleContainer(node) {
const owned = node.$$container$$;
if (owned && owned.responsibleForOwnerRequests) {
return owned;
}
return DI.findParentContainer(node);
},
/**
* Find the dependency injection container up the DOM tree from this node.
* @param node - The node to find the parent container for.
* @returns The parent container of this node.
* @remarks
* This will be the same as the responsible container if the specified node
* does not itself host a container configured with responsibleForOwnerRequests.
*/
findParentContainer(node) {
const event = new CustomEvent(DILocateParentEventType, {
bubbles: true,
composed: true,
cancelable: true,
detail: { container: void 0 },
});
node.dispatchEvent(event);
return event.detail.container || DI.getOrCreateDOMContainer();
},
/**
* Returns a dependency injection container if one is explicitly owned by the specified
* node. If one is not owned, then a new container is created and assigned to the node.
* @param node - The node to find or create the container for.
* @param config - The configuration for the container if one needs to be created.
* @returns The located or created container.
* @remarks
* This API does not search for a responsible or parent container. It looks only for a container
* directly defined on the specified node and creates one at that location if one does not
* already exist.
*/
getOrCreateDOMContainer(node, config) {
if (!node) {
return (rootDOMContainer ||
(rootDOMContainer = new ContainerImpl(null, Object.assign({}, ContainerConfiguration.default, config, {
parentLocator: () => null,
}))));
}
return (node.$$container$$ ||
new ContainerImpl(node, Object.assign({}, ContainerConfiguration.default, config, {
parentLocator: DI.findParentContainer,
})));
},
/**
* Gets the "design:paramtypes" metadata for the specified type.
* @param Type - The type to get the metadata for.
* @returns The metadata array or undefined if no metadata is found.
*/
getDesignParamtypes: getParamTypes("design:paramtypes"),
/**
* Gets the "di:paramtypes" metadata for the specified type.
* @param Type - The type to get the metadata for.
* @returns The metadata array or undefined if no metadata is found.
*/
getAnnotationParamtypes: getParamTypes("di:paramtypes"),
/**
*
* @param Type - Gets the "di:paramtypes" metadata for the specified type. If none is found,
* an empty metadata array is created and added.
* @returns The metadata array.
*/
getOrCreateAnnotationParamTypes(Type) {
let annotationParamtypes = this.getAnnotationParamtypes(Type);
if (annotationParamtypes === void 0) {
Reflect.defineMetadata("di:paramtypes", (annotationParamtypes = []), Type);
}
return annotationParamtypes;
},
/**
* Gets the dependency keys representing what is needed to instantiate the specified type.
* @param Type - The type to get the dependencies for.
* @returns An array of dependency keys.
*/
getDependencies(Type) {
// Note: Every detail of this getDependencies method is pretty deliberate at the moment, and probably not yet 100% tested from every possible angle,
// so be careful with making changes here as it can have a huge impact on complex end user apps.
// Preferably, only make changes to the dependency resolution process via a RFC.
let dependencies = dependencyLookup.get(Type);
if (dependencies === void 0) {
// Type.length is the number of constructor parameters. If this is 0, it could mean the class has an empty constructor
// but it could also mean the class has no constructor at all (in which case it inherits the constructor from the prototype).
// Non-zero constructor length + no paramtypes means emitDecoratorMetadata is off, or the class has no decorator.
// We're not doing anything with the above right now, but it's good to keep in mind for any future issues.
const inject = Type.inject;
if (inject === void 0) {
// design:paramtypes is set by tsc when emitDecoratorMetadata is enabled.
const designParamtypes = DI.getDesignParamtypes(Type);
// di:paramtypes is set by the parameter decorator from DI.createInterface or by @inject
const annotationParamtypes = DI.getAnnotationParamtypes(Type);
if (designParamtypes === void 0) {
if (annotationParamtypes === void 0) {
// Only go up the prototype if neither static inject nor any of the paramtypes is defined, as
// there is no sound way to merge a type's deps with its prototype's deps
const Proto = Object.getPrototypeOf(Type);
if (typeof Proto === "function" && Proto !== Function.prototype) {
dependencies = cloneArrayWithPossibleProps(DI.getDependencies(Proto));
}
else {
dependencies = [];
}
}
else {
// No design:paramtypes so just use the di:paramtypes
dependencies = cloneArrayWithPossibleProps(annotationParamtypes);
}
}
else if (annotationParamtypes === void 0) {
// No di:paramtypes so just use the design:paramtypes
dependencies = cloneArrayWithPossibleProps(designParamtypes);
}
else {
// We've got both, so merge them (in case of conflict on same index, di:paramtypes take precedence)
dependencies = cloneArrayWithPossibleProps(designParamtypes);
let len = annotationParamtypes.length;
let auAnnotationParamtype;
for (let i = 0; i < len; ++i) {
auAnnotationParamtype = annotationParamtypes[i];
if (auAnnotationParamtype !== void 0) {
dependencies[i] = auAnnotationParamtype;
}
}
const keys = Object.keys(annotationParamtypes);
len = keys.length;
let key;
for (let i = 0; i < len; ++i) {
key = keys[i];
if (!isArrayIndex(key)) {
dependencies[key] = annotationParamtypes[key];
}
}
}
}
else {
// Ignore paramtypes if we have static inject
dependencies = cloneArrayWithPossibleProps(inject);
}
dependencyLookup.set(Type, dependencies);
}
return dependencies;
},
/**
* Defines a property on a web component class. The value of this property will
* be resolved from the dependency injection container responsible for the element
* instance, based on where it is connected in the DOM.
* @param target - The target to define the property on.
* @param propertyName - The name of the property to define.
* @param key - The dependency injection key.
* @param respectConnection - Indicates whether or not to update the property value if the
* hosting component is disconnected and then re-connected at a different location in the DOM.
* @remarks
* The respectConnection option is only applicable to elements that descend from FASTElement.
*/
defineProperty(target, propertyName, key, respectConnection = false) {
const diPropertyKey = `$di_${propertyName}`;
Reflect.defineProperty(target, propertyName, {
get: function () {
let value = this[diPropertyKey];
if (value === void 0) {
const container = this instanceof HTMLElement
? DI.findResponsibleContainer(this)
: DI.getOrCreateDOMContainer();
value = container.get(key);
this[diPropertyKey] = value;
if (respectConnection && this instanceof FASTElement) {
const notifier = this.$fastController;
const handleChange = () => {
const newContainer = DI.findResponsibleContainer(this);
const newValue = newContainer.get(key);
const oldValue = this[diPropertyKey];
if (newValue !== oldValue) {
this[diPropertyKey] = value;
notifier.notify(propertyName);
}
};
notifier.subscribe({ handleChange }, "isConnected");
}
}
return value;
},
});
},
/**
* Creates a dependency injection key.
* @param nameConfigOrCallback - A friendly name for the key or a lambda that configures a
* default resolution for the dependency.
* @param configuror - If a friendly name was provided for the first parameter, then an optional
* lambda that configures a default resolution for the dependency can be provided second.
* @returns The created key.
* @remarks
* The created key can be used as a property decorator or constructor parameter decorator,
* in addition to its standard use in an inject array or through direct container APIs.
*/
createInterface(nameConfigOrCallback, configuror) {
const configure = typeof nameConfigOrCallback === "function"
? nameConfigOrCallback
: configuror;
const friendlyName = typeof nameConfigOrCallback === "string"
? nameConfigOrCallback
: nameConfigOrCallback && "friendlyName" in nameConfigOrCallback
? nameConfigOrCallback.friendlyName || defaultFriendlyName
: defaultFriendlyName;
const respectConnection = typeof nameConfigOrCallback === "string"
? false
: nameConfigOrCallback && "respectConnection" in nameConfigOrCallback
? nameConfigOrCallback.respectConnection || false
: false;
const Interface = function (target, property, index) {
if (target == null || new.target !== undefined) {
throw new Error(`No registration for interface: '${Interface.friendlyName}'`);
}
if (property) {
DI.defineProperty(target, property, Interface, respectConnection);
}
else {
const annotationParamtypes = DI.getOrCreateAnnotationParamTypes(target);
annotationParamtypes[index] = Interface;
}
};
Interface.$isInterface = true;
Interface.friendlyName = friendlyName == null ? "(anonymous)" : friendlyName;
if (configure != null) {
Interface.register = function (container, key) {
return configure(new ResolverBuilder(container, key !== null && key !== void 0 ? key : Interface));
};
}
Interface.toString = function toString() {
return `InterfaceSymbol<${Interface.friendlyName}>`;
};
return Interface;
},
/**
* A decorator that specifies what to inject into its target.
* @param dependencies - The dependencies to inject.
* @returns The decorator to be applied to the target class.
* @remarks
* The decorator can be used to decorate a class, listing all of the classes dependencies.
* Or it can be used to decorate a constructor paramter, indicating what to inject for that
* parameter.
* Or it can be used for a web component property, indicating what that property should resolve to.
*/
inject(...dependencies) {
return function (target, key, descriptor) {
if (typeof descriptor === "number") {
// It's a parameter decorator.
const annotationParamtypes = DI.getOrCreateAnnotationParamTypes(target);
const dep = dependencies[0];
if (dep !== void 0) {
annotationParamtypes[descriptor] = dep;
}
}
else if (key) {
DI.defineProperty(target, key, dependencies[0]);
}
else {
const annotationParamtypes = descriptor
? DI.getOrCreateAnnotationParamTypes(descriptor.value)
: DI.getOrCreateAnnotationParamTypes(target);
let dep;
for (let i = 0; i < dependencies.length; ++i) {
dep = dependencies[i];
if (dep !== void 0) {
annotationParamtypes[i] = dep;
}
}
}
};
},
/**
* Registers the `target` class as a transient dependency; each time the dependency is resolved
* a new instance will be created.
*
* @param target - The class / constructor function to register as transient.
* @returns The same class, with a static `register` method that takes a container and returns the appropriate resolver.
*
* @example
* On an existing class
* ```ts
* class Foo { }
* DI.transient(Foo);
* ```
*
* @example
* Inline declaration
*
* ```ts
* const Foo = DI.transient(class { });
* // Foo is now strongly typed with register
* Foo.register(container);
* ```
*
* @public
*/
transient(target) {
target.register = function register(container) {
const registration = Registration.transient(target, target);
return registration.register(container);
};
target.registerInRequestor = false;
return target;
},
/**
* Registers the `target` class as a singleton dependency; the class will only be created once. Each
* consecutive time the dependency is resolved, the same instance will be returned.
*
* @param target - The class / constructor function to register as a singleton.
* @returns The same class, with a static `register` method that takes a container and returns the appropriate resolver.
* @example
* On an existing class
* ```ts
* class Foo { }
* DI.singleton(Foo);
* ```
*
* @example
* Inline declaration
* ```ts
* const Foo = DI.singleton(class { });
* // Foo is now strongly typed with register
* Foo.register(container);
* ```
*
* @public
*/
singleton(target, options = defaultSingletonOptions) {
target.register = function register(container) {
const registration = Registration.singleton(target, target);
return registration.register(container);
};
target.registerInRequestor = options.scoped;
return target;
},
});
/**
* The interface key that resolves the dependency injection container itself.
* @public
*/
const Container = DI.createInterface("Container");
/**
* The interface key that resolves the service locator itself.
* @public
*/
const ServiceLocator = (/* unused pure expression or super */ null && (Container));
function createResolver(getter) {
return function (key) {
const resolver = function (target, property, descriptor) {
DI.inject(resolver)(target, property, descriptor);
};
resolver.$isResolver = true;
resolver.resolve = function (handler, requestor) {
return getter(key, handler, requestor);
};
return resolver;
};
}
/**
* A decorator that specifies what to inject into its target.
* @param dependencies - The dependencies to inject.
* @returns The decorator to be applied to the target class.
* @remarks
* The decorator can be used to decorate a class, listing all of the classes dependencies.
* Or it can be used to decorate a constructor paramter, indicating what to inject for that
* parameter.
* Or it can be used for a web component property, indicating what that property should resolve to.
*
* @public
*/
const inject = DI.inject;
function transientDecorator(target) {
return DI.transient(target);
}
function di_transient(target) {
return target == null ? transientDecorator : transientDecorator(target);
}
const defaultSingletonOptions = { scoped: false };
function singletonDecorator(target) {
return DI.singleton(target);
}
/**
* @public
*/
function singleton(targetOrOptions) {
if (typeof targetOrOptions === "function") {
return DI.singleton(targetOrOptions);
}
return function ($target) {
return DI.singleton($target, targetOrOptions);
};
}
function createAllResolver(getter) {
return function (key, searchAncestors) {
searchAncestors = !!searchAncestors;
const resolver = function (target, property, descriptor) {
DI.inject(resolver)(target, property, descriptor);
};
resolver.$isResolver = true;
resolver.resolve = function (handler, requestor) {
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
return getter(key, handler, requestor, searchAncestors);
};
return resolver;
};
}
/**
* A decorator and DI resolver that will resolve an array of all dependencies
* registered with the specified key.
* @param key - The key to resolve all dependencies for.
* @param searchAncestors - [optional] Indicates whether to search ancestor containers.
* @public
*/
const di_all = createAllResolver((key, handler, requestor, searchAncestors) => requestor.getAll(key, searchAncestors));
/**
* A decorator that lazily injects a dependency depending on whether the `Key` is present at the time of function call.
*
* @example
* You need to make your argument a function that returns the type, for example
* ```ts
* class Foo {
* constructor( @lazy('random') public random: () => number )
* }
* const foo = container.get(Foo); // instanceof Foo
* foo.random(); // throws
* ```
* would throw an exception because you haven't registered `'random'` before calling the method.
* @example
* This, would give you a new 'Math.random()' number each time.
* ```ts
* class Foo {
* constructor( @lazy('random') public random: () => random )
* }
* container.register(Registration.callback('random', Math.random ));
* container.get(Foo).random(); // some random number
* container.get(Foo).random(); // another random number
* ```
*
* `@lazy` does not manage the lifecycle of the underlying key. If you want a singleton, you have to register as a
* `singleton`, `transient` would also behave as you would expect, providing you a new instance each time.
*
* @param key - The key to lazily resolve.
* see {@link DI.createInterface} on interactions with interfaces
*
* @public
*/
const lazy = createResolver((key, handler, requestor) => {
return () => requestor.get(key);
});
/**
* A decorator that allows you to optionally inject a dependency depending on whether the [[`Key`]] is present, for example:
* @example
* ```ts
* class Foo {
* constructor( @inject('mystring') public str: string = 'somestring' )
* }
* container.get(Foo); // throws
* ```
* would fail
*
* @example
* ```ts
* class Foo {
* constructor( @optional('mystring') public str: string = 'somestring' )
* }
* container.get(Foo).str // somestring
* ```
* if you use it without a default it will inject `undefined`, so remember to mark your input type as
* possibly `undefined`!
*
* @param key - The key to optionally resolve.
* see {@link DI.createInterface} on interactions with interfaces
*
* @public
*/
const optional = createResolver((key, handler, requestor) => {
if (requestor.has(key, true)) {
return requestor.get(key);
}
else {
return undefined;
}
});
/**
* A decorator that tells the container not to try to inject a dependency.
*
* @public
*/
function ignore(target, property, descriptor) {
DI.inject(ignore)(target, property, descriptor);
}
// Hack: casting below used to prevent TS from generate a namespace which can't be commented
// and results in documentation validation errors.
ignore.$isResolver = true;
ignore.resolve = () => undefined;
/**
* A decorator that indicates that a new instance should be injected scoped to the
* container that requested the instance.
* @param key - The dependency key for the new instance.
* @remarks
* This creates a resolver with an instance strategy pointing to the new instance, effectively
* making this a singleton, scoped to the container or DOM's subtree.
*
* @public
*/
const newInstanceForScope = createResolver((key, handler, requestor) => {
const instance = createNewInstance(key, handler);
const resolver = new ResolverImpl(key, 0 /* instance */, instance);
requestor.registerResolver(key, resolver);
return instance;
});
/**
* A decorator that indicates that a new instance should be injected.
* @param key - The dependency key for the new instance.
* @remarks
* The instance is not internally cached with a resolver as newInstanceForScope does.
*
* @public
*/
const newInstanceOf = createResolver((key, handler, _requestor) => createNewInstance(key, handler));
function createNewInstance(key, handler) {
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
return handler.getFactory(key).construct(handler);
}
/** @internal */
class ResolverImpl {
constructor(key, strategy, state) {
this.key = key;
this.strategy = strategy;
this.state = state;
this.resolving = false;
}
get $isResolver() {
return true;
}
register(container) {
return container.registerResolver(this.key, this);
}
resolve(handler, requestor) {
switch (this.strategy) {
case 0 /* instance */:
return this.state;
case 1 /* singleton */: {
if (this.resolving) {
throw new Error(`Cyclic dependency found: ${this.state.name}`);
}
this.resolving = true;
this.state = handler
.getFactory(this.state)
.construct(requestor);
this.strategy = 0 /* instance */;
this.resolving = false;
return this.state;
}
case 2 /* transient */: {
// Always create transients from the requesting container
const factory = handler.getFactory(this.state);
if (factory === null) {
throw new Error(`Resolver for ${String(this.key)} returned a null factory`);
}
return factory.construct(requestor);
}
case 3 /* callback */:
return this.state(handler, requestor, this);
case 4 /* array */:
return this.state[0].resolve(handler, requestor);
case 5 /* alias */:
return requestor.get(this.state);
default:
throw new Error(`Invalid resolver strategy specified: ${this.strategy}.`);
}
}
getFactory(container) {
var _a, _b, _c;
switch (this.strategy) {
case 1 /* singleton */:
case 2 /* transient */:
return container.getFactory(this.state);
case 5 /* alias */:
return (_c = (_b = (_a = container.getResolver(this.state)) === null || _a === void 0 ? void 0 : _a.getFactory) === null || _b === void 0 ? void 0 : _b.call(_a, container)) !== null && _c !== void 0 ? _c : null;
default:
return null;
}
}
}
function containerGetKey(d) {
return this.get(d);
}
function transformInstance(inst, transform) {
return transform(inst);
}
/** @internal */
class FactoryImpl {
constructor(Type, dependencies) {
this.Type = Type;
this.dependencies = dependencies;
this.transformers = null;
}
construct(container, dynamicDependencies) {
let instance;
if (dynamicDependencies === void 0) {
instance = new this.Type(...this.dependencies.map(containerGetKey, container));
}
else {
instance = new this.Type(...this.dependencies.map(containerGetKey, container), ...dynamicDependencies);
}
if (this.transformers == null) {
return instance;
}
return this.transformers.reduce(transformInstance, instance);
}
registerTransformer(transformer) {
(this.transformers || (this.transformers = [])).push(transformer);
}
}
const containerResolver = {
$isResolver: true,
resolve(handler, requestor) {
return requestor;
},
};
function isRegistry(obj) {
return typeof obj.register === "function";
}
function isSelfRegistry(obj) {
return isRegistry(obj) && typeof obj.registerInRequestor === "boolean";
}
function isRegisterInRequester(obj) {
return isSelfRegistry(obj) && obj.registerInRequestor;
}
function isClass(obj) {
return obj.prototype !== void 0;
}
const InstrinsicTypeNames = new Set([
"Array",
"ArrayBuffer",
"Boolean",
"DataView",
"Date",
"Error",
"EvalError",
"Float32Array",
"Float64Array",
"Function",
"Int8Array",
"Int16Array",
"Int32Array",
"Map",
"Number",
"Object",
"Promise",
"RangeError",
"ReferenceError",
"RegExp",
"Set",
"SharedArrayBuffer",
"String",
"SyntaxError",
"TypeError",
"Uint8Array",
"Uint8ClampedArray",
"Uint16Array",
"Uint32Array",
"URIError",
"WeakMap",
"WeakSet",
]);
const DILocateParentEventType = "__DI_LOCATE_PARENT__";
const factories = new Map();
/**
* @internal
*/
class ContainerImpl {
constructor(owner, config) {
this.owner = owner;
this.config = config;
this._parent = void 0;
this.registerDepth = 0;
this.context = null;
if (owner !== null) {
owner.$$container$$ = this;
}
this.resolvers = new Map();
this.resolvers.set(Container, containerResolver);
if (owner instanceof Node) {
owner.addEventListener(DILocateParentEventType, (e) => {
if (e.composedPath()[0] !== this.owner) {
e.detail.container = this;
e.stopImmediatePropagation();
}
});
}
}
get parent() {
if (this._parent === void 0) {
this._parent = this.config.parentLocator(this.owner);
}
return this._parent;
}
get depth() {
return this.parent === null ? 0 : this.parent.depth + 1;
}
get responsibleForOwnerRequests() {
return this.config.responsibleForOwnerRequests;
}
registerWithContext(context, ...params) {
this.context = context;
this.register(...params);
this.context = null;
return this;
}
register(...params) {
if (++this.registerDepth === 100) {
throw new Error("Unable to autoregister dependency");
// Most likely cause is trying to register a plain object that does not have a
// register method and is not a class constructor
}
let current;
let keys;
let value;
let j;
let jj;
const context = this.context;
for (let i = 0, ii = params.length; i < ii; ++i) {
current = params[i];
if (!isObject(current)) {
continue;
}
if (isRegistry(current)) {
current.register(this, context);
}
else if (isClass(current)) {
Registration.singleton(current, current).register(this);
}
else {
keys = Object.keys(current);
j = 0;
jj = keys.length;
for (; j < jj; ++j) {
value = current[keys[j]];
if (!isObject(value)) {
continue;
}
// note: we could remove this if-branch and call this.register directly
// - the extra check is just a perf tweak to create fewer unnecessary arrays by the spread operator
if (isRegistry(value)) {
value.register(this, context);
}
else {
this.register(value);
}
}
}
}
--this.registerDepth;
return this;
}
registerResolver(key, resolver) {
validateKey(key);
const resolvers = this.resolvers;
const result = resolvers.get(key);
if (result == null) {
resolvers.set(key, resolver);
}
else if (result instanceof ResolverImpl &&
result.strategy === 4 /* array */) {
result.state.push(resolver);
}
else {
resolvers.set(key, new ResolverImpl(key, 4 /* array */, [result, resolver]));
}
return resolver;
}
registerTransformer(key, transformer) {
const resolver = this.getResolver(key);
if (resolver == null) {
return false;
}
if (resolver.getFactory) {
const factory = resolver.getFactory(this);
if (factory == null) {
return false;
}
// This type cast is a bit of a hacky one, necessary due to the duplicity of IResolverLike.
// Problem is that that interface's type arg can be of type Key, but the getFactory method only works on
// type Constructable. So the return type of that optional method has this additional constraint, which
// seems to confuse the type checker.
factory.registerTransformer(transformer);
return true;
}
return false;
}
getResolver(key, autoRegister = true) {
validateKey(key);
if (key.resolve !== void 0) {
return key;
}
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
let current = this;
let resolver;
while (current != null) {
resolver = current.resolvers.get(key);
if (resolver == null) {
if (current.parent == null) {
const handler = isRegisterInRequester(key)
? this
: current;
return autoRegister ? this.jitRegister(key, handler) : null;
}
current = current.parent;
}
else {
return resolver;
}
}
return null;
}
has(key, searchAncestors = false) {
return this.resolvers.has(key)
? true
: searchAncestors && this.parent != null
? this.parent.has(key, true)
: false;
}
get(key) {
validateKey(key);
if (key.$isResolver) {
return key.resolve(this, this);
}
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
let current = this;
let resolver;
while (current != null) {
resolver = current.resolvers.get(key);
if (resolver == null) {
if (current.parent == null) {
const handler = isRegisterInRequester(key)
? this
: current;
resolver = this.jitRegister(key, handler);
return resolver.resolve(current, this);
}
current = current.parent;
}
else {
return resolver.resolve(current, this);
}
}
throw new Error(`Unable to resolve key: ${String(key)}`);
}
getAll(key, searchAncestors = false) {
validateKey(key);
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
const requestor = this;
let current = requestor;
let resolver;
if (searchAncestors) {
let resolutions = emptyArray;
while (current != null) {
resolver = current.resolvers.get(key);
if (resolver != null) {
resolutions = resolutions.concat(
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
buildAllResponse(resolver, current, requestor));
}
current = current.parent;
}
return resolutions;
}
else {
while (current != null) {
resolver = current.resolvers.get(key);
if (resolver == null) {
current = current.parent;
if (current == null) {
return emptyArray;
}
}
else {
return buildAllResponse(resolver, current, requestor);
}
}
}
return emptyArray;
}
getFactory(Type) {
let factory = factories.get(Type);
if (factory === void 0) {
if (isNativeFunction(Type)) {
throw new Error(`${Type.name} is a native function and therefore cannot be safely constructed by DI. If this is intentional, please use a callback or cachedCallback resolver.`);
}
factories.set(Type, (factory = new FactoryImpl(Type, DI.getDependencies(Type))));
}
return factory;
}
registerFactory(key, factory) {
factories.set(key, factory);
}
createChild(config) {
return new ContainerImpl(null, Object.assign({}, this.config, config, { parentLocator: () => this }));
}
jitRegister(keyAsValue, handler) {
if (typeof keyAsValue !== "function") {
throw new Error(`Attempted to jitRegister something that is not a constructor: '${keyAsValue}'. Did you forget to register this dependency?`);
}
if (InstrinsicTypeNames.has(keyAsValue.name)) {
throw new Error(`Attempted to jitRegister an intrinsic type: ${keyAsValue.name}. Did you forget to add @inject(Key)`);
}
if (isRegistry(keyAsValue)) {
const registrationResolver = keyAsValue.register(handler);
if (!(registrationResolver instanceof Object) ||
registrationResolver.resolve == null) {
const newResolver = handler.resolvers.get(keyAsValue);
if (newResolver != void 0) {
return newResolver;
}
throw new Error("A valid resolver was not returned from the static register method");
}
return registrationResolver;
}
else if (keyAsValue.$isInterface) {
throw new Error(`Attempted to jitRegister an interface: ${keyAsValue.friendlyName}`);
}
else {
const resolver = this.config.defaultResolver(keyAsValue, handler);
handler.resolvers.set(keyAsValue, resolver);
return resolver;
}
}
}
const cache = new WeakMap();
function cacheCallbackResult(fun) {
return function (handler, requestor, resolver) {
if (cache.has(resolver)) {
return cache.get(resolver);
}
const t = fun(handler, requestor, resolver);
cache.set(resolver, t);
return t;
};
}
/**
* You can use the resulting Registration of any of the factory methods
* to register with the container.
*
* @example
* ```
* class Foo {}
* const container = DI.createContainer();
* container.register(Registration.instance(Foo, new Foo()));
* container.get(Foo);
* ```
*
* @public
*/
const Registration = Object.freeze({
/**
* Allows you to pass an instance.
* Every time you request this {@link Key} you will get this instance back.
*
* @example
* ```
* Registration.instance(Foo, new Foo()));
* ```
*
* @param key - The key to register the instance under.
* @param value - The instance to return when the key is requested.
*/
instance(key, value) {
return new ResolverImpl(key, 0 /* instance */, value);
},
/**
* Creates an instance from the class.
* Every time you request this {@link Key} you will get the same one back.
*
* @example
* ```
* Registration.singleton(Foo, Foo);
* ```
*
* @param key - The key to register the singleton under.
* @param value - The class to instantiate as a singleton when first requested.
*/
singleton(key, value) {
return new ResolverImpl(key, 1 /* singleton */, value);
},
/**
* Creates an instance from a class.
* Every time you request this {@link Key} you will get a new instance.
*
* @example
* ```
* Registration.instance(Foo, Foo);
* ```
*
* @param key - The key to register the instance type under.
* @param value - The class to instantiate each time the key is requested.
*/
transient(key, value) {
return new ResolverImpl(key, 2 /* transient */, value);
},
/**
* Delegates to a callback function to provide the dependency.
* Every time you request this {@link Key} the callback will be invoked to provide
* the dependency.
*
* @example
* ```
* Registration.callback(Foo, () => new Foo());
* Registration.callback(Bar, (c: Container) => new Bar(c.get(Foo)));
* ```
*
* @param key - The key to register the callback for.
* @param callback - The function that is expected to return the dependency.
*/
callback(key, callback) {
return new ResolverImpl(key, 3 /* callback */, callback);
},
/**
* Delegates to a callback function to provide the dependency and then caches the
* dependency for future requests.
*
* @example
* ```
* Registration.cachedCallback(Foo, () => new Foo());
* Registration.cachedCallback(Bar, (c: Container) => new Bar(c.get(Foo)));
* ```
*
* @param key - The key to register the callback for.
* @param callback - The function that is expected to return the dependency.
* @remarks
* If you pass the same Registration to another container, the same cached value will be used.
* Should all references to the resolver returned be removed, the cache will expire.
*/
cachedCallback(key, callback) {
return new ResolverImpl(key, 3 /* callback */, cacheCallbackResult(callback));
},
/**
* Creates an alternate {@link Key} to retrieve an instance by.
*
* @example
* ```
* Register.singleton(Foo, Foo)
* Register.aliasTo(Foo, MyFoos);
*
* container.getAll(MyFoos) // contains an instance of Foo
* ```
*
* @param originalKey - The original key that has been registered.
* @param aliasKey - The alias to the original key.
*/
aliasTo(originalKey, aliasKey) {
return new ResolverImpl(aliasKey, 5 /* alias */, originalKey);
},
});
/** @internal */
function validateKey(key) {
if (key === null || key === void 0) {
throw new Error("key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?");
}
}
function buildAllResponse(resolver, handler, requestor) {
if (resolver instanceof ResolverImpl &&
resolver.strategy === 4 /* array */) {
const state = resolver.state;
let i = state.length;
const results = new Array(i);
while (i--) {
results[i] = state[i].resolve(handler, requestor);
}
return results;
}
return [resolver.resolve(handler, requestor)];
}
const defaultFriendlyName = "(anonymous)";
function isObject(value) {
return (typeof value === "object" && value !== null) || typeof value === "function";
}
/**
* Determine whether the value is a native function.
*
* @param fn - The function to check.
* @returns `true` is the function is a native function, otherwise `false`
*/
const isNativeFunction = (function () {
const lookup = new WeakMap();
let isNative = false;
let sourceText = "";
let i = 0;
return function (fn) {
isNative = lookup.get(fn);
if (isNative === void 0) {
sourceText = fn.toString();
i = sourceText.length;
// http://www.ecma-international.org/ecma-262/#prod-NativeFunction
isNative =
// 29 is the length of 'function () { [native code] }' which is the smallest length of a native function string
i >= 29 &&
// 100 seems to be a safe upper bound of the max length of a native function. In Chrome and FF it's 56, in Edge it's 61.
i <= 100 &&
// This whole heuristic *could* be tricked by a comment. Do we need to care about that?
sourceText.charCodeAt(i - 1) === 0x7d && // }
// TODO: the spec is a little vague about the precise constraints, so we do need to test this across various browsers to make sure just one whitespace is a safe assumption.
sourceText.charCodeAt(i - 2) <= 0x20 && // whitespace
sourceText.charCodeAt(i - 3) === 0x5d && // ]
sourceText.charCodeAt(i - 4) === 0x65 && // e
sourceText.charCodeAt(i - 5) === 0x64 && // d
sourceText.charCodeAt(i - 6) === 0x6f && // o
sourceText.charCodeAt(i - 7) === 0x63 && // c
sourceText.charCodeAt(i - 8) === 0x20 && //
sourceText.charCodeAt(i - 9) === 0x65 && // e
sourceText.charCodeAt(i - 10) === 0x76 && // v
sourceText.charCodeAt(i - 11) === 0x69 && // i
sourceText.charCodeAt(i - 12) === 0x74 && // t
sourceText.charCodeAt(i - 13) === 0x61 && // a
sourceText.charCodeAt(i - 14) === 0x6e && // n
sourceText.charCodeAt(i - 15) === 0x58; // [
lookup.set(fn, isNative);
}
return isNative;
};
})();
const isNumericLookup = {};
function isArrayIndex(value) {
switch (typeof value) {
case "number":
return value >= 0 && (value | 0) === value;
case "string": {
const result = isNumericLookup[value];
if (result !== void 0) {
return result;
}
const length = value.length;
if (length === 0) {
return (isNumericLookup[value] = false);
}
let ch = 0;
for (let i = 0; i < length; ++i) {
ch = value.charCodeAt(i);
if ((i === 0 && ch === 0x30 && length > 1) /* must not start with 0 */ ||
ch < 0x30 /* 0 */ ||
ch > 0x39 /* 9 */) {
return (isNumericLookup[value] = false);
}
}
return (isNumericLookup[value] = true);
}
default:
return false;
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/design-system/component-presentation.js
function presentationKeyFromTag(tagName) {
return `${tagName.toLowerCase()}:presentation`;
}
const presentationRegistry = new Map();
/**
* An API gateway to component presentation features.
* @public
*/
const ComponentPresentation = Object.freeze({
/**
* Defines a component presentation for an element.
* @param tagName - The element name to define the presentation for.
* @param presentation - The presentation that will be applied to matching elements.
* @param container - The dependency injection container to register the configuration in.
* @public
*/
define(tagName, presentation, container) {
const key = presentationKeyFromTag(tagName);
const existing = presentationRegistry.get(key);
if (existing === void 0) {
presentationRegistry.set(key, presentation);
}
else {
// false indicates that we have more than one presentation
// registered for a tagName and we must resolve through DI
presentationRegistry.set(key, false);
}
container.register(Registration.instance(key, presentation));
},
/**
* Finds a component presentation for the specified element name,
* searching the DOM hierarchy starting from the provided element.
* @param tagName - The name of the element to locate the presentation for.
* @param element - The element to begin the search from.
* @returns The component presentation or null if none is found.
* @public
*/
forTag(tagName, element) {
const key = presentationKeyFromTag(tagName);
const existing = presentationRegistry.get(key);
if (existing === false) {
const container = DI.findResponsibleContainer(element);
return container.get(key);
}
return existing || null;
},
});
/**
* The default implementation of ComponentPresentation, used by FoundationElement.
* @public
*/
class DefaultComponentPresentation {
/**
* Creates an instance of DefaultComponentPresentation.
* @param template - The template to apply to the element.
* @param styles - The styles to apply to the element.
* @public
*/
constructor(template, styles) {
this.template = template || null;
this.styles =
styles === void 0
? null
: Array.isArray(styles)
? ElementStyles.create(styles)
: styles instanceof ElementStyles
? styles
: ElementStyles.create([styles]);
}
/**
* Applies the presentation details to the specified element.
* @param element - The element to apply the presentation details to.
* @public
*/
applyTo(element) {
const controller = element.$fastController;
if (controller.template === null) {
controller.template = this.template;
}
if (controller.styles === null) {
controller.styles = this.styles;
}
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/foundation-element/foundation-element.js
/**
* Defines a foundation element class that:
* 1. Connects the element to its ComponentPresentation
* 2. Allows resolving the element template from the instance or ComponentPresentation
* 3. Allows resolving the element styles from the instance or ComponentPresentation
*
* @public
*/
class FoundationElement extends FASTElement {
constructor() {
super(...arguments);
this._presentation = void 0;
}
/**
* A property which resolves the ComponentPresentation instance
* for the current component.
* @public
*/
get $presentation() {
if (this._presentation === void 0) {
this._presentation = ComponentPresentation.forTag(this.tagName, this);
}
return this._presentation;
}
templateChanged() {
if (this.template !== undefined) {
this.$fastController.template = this.template;
}
}
stylesChanged() {
if (this.styles !== undefined) {
this.$fastController.styles = this.styles;
}
}
/**
* The connected callback for this FASTElement.
* @remarks
* This method is invoked by the platform whenever this FoundationElement
* becomes connected to the document.
* @public
*/
connectedCallback() {
if (this.$presentation !== null) {
this.$presentation.applyTo(this);
}
super.connectedCallback();
}
/**
* Defines an element registry function with a set of element definition defaults.
* @param elementDefinition - The definition of the element to create the registry
* function for.
* @public
*/
static compose(elementDefinition) {
return (overrideDefinition = {}) => new FoundationElementRegistry(this === FoundationElement
? class extends FoundationElement {
}
: this, elementDefinition, overrideDefinition);
}
}
__decorate([
observable
], FoundationElement.prototype, "template", void 0);
__decorate([
observable
], FoundationElement.prototype, "styles", void 0);
function resolveOption(option, context, definition) {
if (typeof option === "function") {
return option(context, definition);
}
return option;
}
/**
* Registry capable of defining presentation properties for a DOM Container hierarchy.
*
* @internal
*/
/* eslint-disable @typescript-eslint/no-unused-vars */
class FoundationElementRegistry {
constructor(type, elementDefinition, overrideDefinition) {
this.type = type;
this.elementDefinition = elementDefinition;
this.overrideDefinition = overrideDefinition;
this.definition = Object.assign(Object.assign({}, this.elementDefinition), this.overrideDefinition);
}
register(container, context) {
const definition = this.definition;
const overrideDefinition = this.overrideDefinition;
const prefix = definition.prefix || context.elementPrefix;
const name = `${prefix}-${definition.baseName}`;
context.tryDefineElement({
name,
type: this.type,
baseClass: this.elementDefinition.baseClass,
callback: x => {
const presentation = new DefaultComponentPresentation(resolveOption(definition.template, x, definition), resolveOption(definition.styles, x, definition));
x.definePresentation(presentation);
let shadowOptions = resolveOption(definition.shadowOptions, x, definition);
if (x.shadowRootMode) {
// If the design system has overridden the shadow root mode, we need special handling.
if (shadowOptions) {
// If there are shadow options present in the definition, then
// either the component itself has specified an option or the
// registry function has overridden it.
if (!overrideDefinition.shadowOptions) {
// There were shadow options provided by the component and not overridden by
// the registry.
shadowOptions.mode = x.shadowRootMode;
}
}
else if (shadowOptions !== null) {
// If the component author did not provide shadow options,
// and did not null them out (light dom opt-in) then they
// were relying on the FASTElement default. So, if the
// design system provides a mode, we need to create the options
// to override the default.
shadowOptions = { mode: x.shadowRootMode };
}
}
x.defineElement({
elementOptions: resolveOption(definition.elementOptions, x, definition),
shadowOptions,
attributes: resolveOption(definition.attributes, x, definition),
});
},
});
}
}
/* eslint-enable @typescript-eslint/no-unused-vars */
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/html-directive.js
/**
* Instructs the template engine to apply behavior to a node.
* @public
*/
class HTMLDirective {
constructor() {
/**
* The index of the DOM node to which the created behavior will apply.
*/
this.targetIndex = 0;
}
}
/**
* A {@link HTMLDirective} that targets a named attribute or property on a node.
* @public
*/
class TargetedHTMLDirective extends HTMLDirective {
constructor() {
super(...arguments);
/**
* Creates a placeholder string based on the directive's index within the template.
* @param index - The index of the directive within the template.
*/
this.createPlaceholder = DOM.createInterpolationPlaceholder;
}
}
/**
* A directive that attaches special behavior to an element via a custom attribute.
* @public
*/
class AttachedBehaviorHTMLDirective extends HTMLDirective {
/**
*
* @param name - The name of the behavior; used as a custom attribute on the element.
* @param behavior - The behavior to instantiate and attach to the element.
* @param options - Options to pass to the behavior during creation.
*/
constructor(name, behavior, options) {
super();
this.name = name;
this.behavior = behavior;
this.options = options;
}
/**
* Creates a placeholder string based on the directive's index within the template.
* @param index - The index of the directive within the template.
* @remarks
* Creates a custom attribute placeholder.
*/
createPlaceholder(index) {
return DOM.createCustomAttributePlaceholder(this.name, index);
}
/**
* Creates a behavior for the provided target node.
* @param target - The node instance to create the behavior for.
* @remarks
* Creates an instance of the `behavior` type this directive was constructed with
* and passes the target and options to that `behavior`'s constructor.
*/
createBehavior(target) {
return new this.behavior(target, this.options);
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/binding.js
function normalBind(source, context) {
this.source = source;
this.context = context;
if (this.bindingObserver === null) {
this.bindingObserver = Observable.binding(this.binding, this, this.isBindingVolatile);
}
this.updateTarget(this.bindingObserver.observe(source, context));
}
function triggerBind(source, context) {
this.source = source;
this.context = context;
this.target.addEventListener(this.targetName, this);
}
function normalUnbind() {
this.bindingObserver.disconnect();
this.source = null;
this.context = null;
}
function contentUnbind() {
this.bindingObserver.disconnect();
this.source = null;
this.context = null;
const view = this.target.$fastView;
if (view !== void 0 && view.isComposed) {
view.unbind();
view.needsBindOnly = true;
}
}
function triggerUnbind() {
this.target.removeEventListener(this.targetName, this);
this.source = null;
this.context = null;
}
function updateAttributeTarget(value) {
DOM.setAttribute(this.target, this.targetName, value);
}
function updateBooleanAttributeTarget(value) {
DOM.setBooleanAttribute(this.target, this.targetName, value);
}
function updateContentTarget(value) {
// If there's no actual value, then this equates to the
// empty string for the purposes of content bindings.
if (value === null || value === undefined) {
value = "";
}
// If the value has a "create" method, then it's a template-like.
if (value.create) {
this.target.textContent = "";
let view = this.target.$fastView;
// If there's no previous view that we might be able to
// reuse then create a new view from the template.
if (view === void 0) {
view = value.create();
}
else {
// If there is a previous view, but it wasn't created
// from the same template as the new value, then we
// need to remove the old view if it's still in the DOM
// and create a new view from the template.
if (this.target.$fastTemplate !== value) {
if (view.isComposed) {
view.remove();
view.unbind();
}
view = value.create();
}
}
// It's possible that the value is the same as the previous template
// and that there's actually no need to compose it.
if (!view.isComposed) {
view.isComposed = true;
view.bind(this.source, this.context);
view.insertBefore(this.target);
this.target.$fastView = view;
this.target.$fastTemplate = value;
}
else if (view.needsBindOnly) {
view.needsBindOnly = false;
view.bind(this.source, this.context);
}
}
else {
const view = this.target.$fastView;
// If there is a view and it's currently composed into
// the DOM, then we need to remove it.
if (view !== void 0 && view.isComposed) {
view.isComposed = false;
view.remove();
if (view.needsBindOnly) {
view.needsBindOnly = false;
}
else {
view.unbind();
}
}
this.target.textContent = value;
}
}
function updatePropertyTarget(value) {
this.target[this.targetName] = value;
}
function updateClassTarget(value) {
const classVersions = this.classVersions || Object.create(null);
const target = this.target;
let version = this.version || 0;
// Add the classes, tracking the version at which they were added.
if (value !== null && value !== undefined && value.length) {
const names = value.split(/\s+/);
for (let i = 0, ii = names.length; i < ii; ++i) {
const currentName = names[i];
if (currentName === "") {
continue;
}
classVersions[currentName] = version;
target.classList.add(currentName);
}
}
this.classVersions = classVersions;
this.version = version + 1;
// If this is the first call to add classes, there's no need to remove old ones.
if (version === 0) {
return;
}
// Remove classes from the previous version.
version -= 1;
for (const name in classVersions) {
if (classVersions[name] === version) {
target.classList.remove(name);
}
}
}
/**
* A directive that configures data binding to element content and attributes.
* @public
*/
class HTMLBindingDirective extends TargetedHTMLDirective {
/**
* Creates an instance of BindingDirective.
* @param binding - A binding that returns the data used to update the DOM.
*/
constructor(binding) {
super();
this.binding = binding;
this.bind = normalBind;
this.unbind = normalUnbind;
this.updateTarget = updateAttributeTarget;
this.isBindingVolatile = Observable.isVolatileBinding(this.binding);
}
/**
* Gets/sets the name of the attribute or property that this
* binding is targeting.
*/
get targetName() {
return this.originalTargetName;
}
set targetName(value) {
this.originalTargetName = value;
if (value === void 0) {
return;
}
switch (value[0]) {
case ":":
this.cleanedTargetName = value.substr(1);
this.updateTarget = updatePropertyTarget;
if (this.cleanedTargetName === "innerHTML") {
const binding = this.binding;
this.binding = (s, c) => DOM.createHTML(binding(s, c));
}
break;
case "?":
this.cleanedTargetName = value.substr(1);
this.updateTarget = updateBooleanAttributeTarget;
break;
case "@":
this.cleanedTargetName = value.substr(1);
this.bind = triggerBind;
this.unbind = triggerUnbind;
break;
default:
this.cleanedTargetName = value;
if (value === "class") {
this.updateTarget = updateClassTarget;
}
break;
}
}
/**
* Makes this binding target the content of an element rather than
* a particular attribute or property.
*/
targetAtContent() {
this.updateTarget = updateContentTarget;
this.unbind = contentUnbind;
}
/**
* Creates the runtime BindingBehavior instance based on the configuration
* information stored in the BindingDirective.
* @param target - The target node that the binding behavior should attach to.
*/
createBehavior(target) {
/* eslint-disable-next-line @typescript-eslint/no-use-before-define */
return new BindingBehavior(target, this.binding, this.isBindingVolatile, this.bind, this.unbind, this.updateTarget, this.cleanedTargetName);
}
}
/**
* A behavior that updates content and attributes based on a configured
* BindingDirective.
* @public
*/
class BindingBehavior {
/**
* Creates an instance of BindingBehavior.
* @param target - The target of the data updates.
* @param binding - The binding that returns the latest value for an update.
* @param isBindingVolatile - Indicates whether the binding has volatile dependencies.
* @param bind - The operation to perform during binding.
* @param unbind - The operation to perform during unbinding.
* @param updateTarget - The operation to perform when updating.
* @param targetName - The name of the target attribute or property to update.
*/
constructor(target, binding, isBindingVolatile, bind, unbind, updateTarget, targetName) {
/** @internal */
this.source = null;
/** @internal */
this.context = null;
/** @internal */
this.bindingObserver = null;
this.target = target;
this.binding = binding;
this.isBindingVolatile = isBindingVolatile;
this.bind = bind;
this.unbind = unbind;
this.updateTarget = updateTarget;
this.targetName = targetName;
}
/** @internal */
handleChange() {
this.updateTarget(this.bindingObserver.observe(this.source, this.context));
}
/** @internal */
handleEvent(event) {
ExecutionContext.setEvent(event);
const result = this.binding(this.source, this.context);
ExecutionContext.setEvent(null);
if (result !== true) {
event.preventDefault();
}
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/compiler.js
let sharedContext = null;
class CompilationContext {
addFactory(factory) {
factory.targetIndex = this.targetIndex;
this.behaviorFactories.push(factory);
}
captureContentBinding(directive) {
directive.targetAtContent();
this.addFactory(directive);
}
reset() {
this.behaviorFactories = [];
this.targetIndex = -1;
}
release() {
/* eslint-disable-next-line @typescript-eslint/no-this-alias */
sharedContext = this;
}
static borrow(directives) {
const shareable = sharedContext || new CompilationContext();
shareable.directives = directives;
shareable.reset();
sharedContext = null;
return shareable;
}
}
function createAggregateBinding(parts) {
if (parts.length === 1) {
return parts[0];
}
let targetName;
const partCount = parts.length;
const finalParts = parts.map((x) => {
if (typeof x === "string") {
return () => x;
}
targetName = x.targetName || targetName;
return x.binding;
});
const binding = (scope, context) => {
let output = "";
for (let i = 0; i < partCount; ++i) {
output += finalParts[i](scope, context);
}
return output;
};
const directive = new HTMLBindingDirective(binding);
directive.targetName = targetName;
return directive;
}
const interpolationEndLength = _interpolationEnd.length;
function parseContent(context, value) {
const valueParts = value.split(_interpolationStart);
if (valueParts.length === 1) {
return null;
}
const bindingParts = [];
for (let i = 0, ii = valueParts.length; i < ii; ++i) {
const current = valueParts[i];
const index = current.indexOf(_interpolationEnd);
let literal;
if (index === -1) {
literal = current;
}
else {
const directiveIndex = parseInt(current.substring(0, index));
bindingParts.push(context.directives[directiveIndex]);
literal = current.substring(index + interpolationEndLength);
}
if (literal !== "") {
bindingParts.push(literal);
}
}
return bindingParts;
}
function compileAttributes(context, node, includeBasicValues = false) {
const attributes = node.attributes;
for (let i = 0, ii = attributes.length; i < ii; ++i) {
const attr = attributes[i];
const attrValue = attr.value;
const parseResult = parseContent(context, attrValue);
let result = null;
if (parseResult === null) {
if (includeBasicValues) {
result = new HTMLBindingDirective(() => attrValue);
result.targetName = attr.name;
}
}
else {
result = createAggregateBinding(parseResult);
}
if (result !== null) {
node.removeAttributeNode(attr);
i--;
ii--;
context.addFactory(result);
}
}
}
function compileContent(context, node, walker) {
const parseResult = parseContent(context, node.textContent);
if (parseResult !== null) {
let lastNode = node;
for (let i = 0, ii = parseResult.length; i < ii; ++i) {
const currentPart = parseResult[i];
const currentNode = i === 0
? node
: lastNode.parentNode.insertBefore(document.createTextNode(""), lastNode.nextSibling);
if (typeof currentPart === "string") {
currentNode.textContent = currentPart;
}
else {
currentNode.textContent = " ";
context.captureContentBinding(currentPart);
}
lastNode = currentNode;
context.targetIndex++;
if (currentNode !== node) {
walker.nextNode();
}
}
context.targetIndex--;
}
}
/**
* Compiles a template and associated directives into a raw compilation
* result which include a cloneable DocumentFragment and factories capable
* of attaching runtime behavior to nodes within the fragment.
* @param template - The template to compile.
* @param directives - The directives referenced by the template.
* @remarks
* The template that is provided for compilation is altered in-place
* and cannot be compiled again. If the original template must be preserved,
* it is recommended that you clone the original and pass the clone to this API.
* @public
*/
function compileTemplate(template, directives) {
const fragment = template.content;
// https://bugs.chromium.org/p/chromium/issues/detail?id=1111864
document.adoptNode(fragment);
const context = CompilationContext.borrow(directives);
compileAttributes(context, template, true);
const hostBehaviorFactories = context.behaviorFactories;
context.reset();
const walker = DOM.createTemplateWalker(fragment);
let node;
while ((node = walker.nextNode())) {
context.targetIndex++;
switch (node.nodeType) {
case 1: // element node
compileAttributes(context, node);
break;
case 3: // text node
compileContent(context, node, walker);
break;
case 8: // comment
if (DOM.isMarker(node)) {
context.addFactory(directives[DOM.extractDirectiveIndexFromMarker(node)]);
}
}
}
let targetOffset = 0;
if (
// If the first node in a fragment is a marker, that means it's an unstable first node,
// because something like a when, repeat, etc. could add nodes before the marker.
// To mitigate this, we insert a stable first node. However, if we insert a node,
// that will alter the result of the TreeWalker. So, we also need to offset the target index.
DOM.isMarker(fragment.firstChild) ||
// Or if there is only one node and a directive, it means the template's content
// is *only* the directive. In that case, HTMLView.dispose() misses any nodes inserted by
// the directive. Inserting a new node ensures proper disposal of nodes added by the directive.
(fragment.childNodes.length === 1 && directives.length)) {
fragment.insertBefore(document.createComment(""), fragment.firstChild);
targetOffset = -1;
}
const viewBehaviorFactories = context.behaviorFactories;
context.release();
return {
fragment,
viewBehaviorFactories,
hostBehaviorFactories,
targetOffset,
};
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/view.js
// A singleton Range instance used to efficiently remove ranges of DOM nodes.
// See the implementation of HTMLView below for further details.
const range = document.createRange();
/**
* The standard View implementation, which also implements ElementView and SyntheticView.
* @public
*/
class HTMLView {
/**
* Constructs an instance of HTMLView.
* @param fragment - The html fragment that contains the nodes for this view.
* @param behaviors - The behaviors to be applied to this view.
*/
constructor(fragment, behaviors) {
this.fragment = fragment;
this.behaviors = behaviors;
/**
* The data that the view is bound to.
*/
this.source = null;
/**
* The execution context the view is running within.
*/
this.context = null;
this.firstChild = fragment.firstChild;
this.lastChild = fragment.lastChild;
}
/**
* Appends the view's DOM nodes to the referenced node.
* @param node - The parent node to append the view's DOM nodes to.
*/
appendTo(node) {
node.appendChild(this.fragment);
}
/**
* Inserts the view's DOM nodes before the referenced node.
* @param node - The node to insert the view's DOM before.
*/
insertBefore(node) {
if (this.fragment.hasChildNodes()) {
node.parentNode.insertBefore(this.fragment, node);
}
else {
const end = this.lastChild;
if (node.previousSibling === end)
return;
const parentNode = node.parentNode;
let current = this.firstChild;
let next;
while (current !== end) {
next = current.nextSibling;
parentNode.insertBefore(current, node);
current = next;
}
parentNode.insertBefore(end, node);
}
}
/**
* Removes the view's DOM nodes.
* The nodes are not disposed and the view can later be re-inserted.
*/
remove() {
const fragment = this.fragment;
const end = this.lastChild;
let current = this.firstChild;
let next;
while (current !== end) {
next = current.nextSibling;
fragment.appendChild(current);
current = next;
}
fragment.appendChild(end);
}
/**
* Removes the view and unbinds its behaviors, disposing of DOM nodes afterward.
* Once a view has been disposed, it cannot be inserted or bound again.
*/
dispose() {
const parent = this.firstChild.parentNode;
const end = this.lastChild;
let current = this.firstChild;
let next;
while (current !== end) {
next = current.nextSibling;
parent.removeChild(current);
current = next;
}
parent.removeChild(end);
const behaviors = this.behaviors;
const oldSource = this.source;
for (let i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].unbind(oldSource);
}
}
/**
* Binds a view's behaviors to its binding source.
* @param source - The binding source for the view's binding behaviors.
* @param context - The execution context to run the behaviors within.
*/
bind(source, context) {
const behaviors = this.behaviors;
if (this.source === source) {
return;
}
else if (this.source !== null) {
const oldSource = this.source;
this.source = source;
this.context = context;
for (let i = 0, ii = behaviors.length; i < ii; ++i) {
const current = behaviors[i];
current.unbind(oldSource);
current.bind(source, context);
}
}
else {
this.source = source;
this.context = context;
for (let i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].bind(source, context);
}
}
}
/**
* Unbinds a view's behaviors from its binding source.
*/
unbind() {
if (this.source === null) {
return;
}
const behaviors = this.behaviors;
const oldSource = this.source;
for (let i = 0, ii = behaviors.length; i < ii; ++i) {
behaviors[i].unbind(oldSource);
}
this.source = null;
}
/**
* Efficiently disposes of a contiguous range of synthetic view instances.
* @param views - A contiguous range of views to be disposed.
*/
static disposeContiguousBatch(views) {
if (views.length === 0) {
return;
}
range.setStartBefore(views[0].firstChild);
range.setEndAfter(views[views.length - 1].lastChild);
range.deleteContents();
for (let i = 0, ii = views.length; i < ii; ++i) {
const view = views[i];
const behaviors = view.behaviors;
const oldSource = view.source;
for (let j = 0, jj = behaviors.length; j < jj; ++j) {
behaviors[j].unbind(oldSource);
}
}
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/template.js
/**
* A template capable of creating HTMLView instances or rendering directly to DOM.
* @public
*/
/* eslint-disable-next-line @typescript-eslint/no-unused-vars */
class ViewTemplate {
/**
* Creates an instance of ViewTemplate.
* @param html - The html representing what this template will instantiate, including placeholders for directives.
* @param directives - The directives that will be connected to placeholders in the html.
*/
constructor(html, directives) {
this.behaviorCount = 0;
this.hasHostBehaviors = false;
this.fragment = null;
this.targetOffset = 0;
this.viewBehaviorFactories = null;
this.hostBehaviorFactories = null;
this.html = html;
this.directives = directives;
}
/**
* Creates an HTMLView instance based on this template definition.
* @param hostBindingTarget - The element that host behaviors will be bound to.
*/
create(hostBindingTarget) {
if (this.fragment === null) {
let template;
const html = this.html;
if (typeof html === "string") {
template = document.createElement("template");
template.innerHTML = DOM.createHTML(html);
const fec = template.content.firstElementChild;
if (fec !== null && fec.tagName === "TEMPLATE") {
template = fec;
}
}
else {
template = html;
}
const result = compileTemplate(template, this.directives);
this.fragment = result.fragment;
this.viewBehaviorFactories = result.viewBehaviorFactories;
this.hostBehaviorFactories = result.hostBehaviorFactories;
this.targetOffset = result.targetOffset;
this.behaviorCount =
this.viewBehaviorFactories.length + this.hostBehaviorFactories.length;
this.hasHostBehaviors = this.hostBehaviorFactories.length > 0;
}
const fragment = this.fragment.cloneNode(true);
const viewFactories = this.viewBehaviorFactories;
const behaviors = new Array(this.behaviorCount);
const walker = DOM.createTemplateWalker(fragment);
let behaviorIndex = 0;
let targetIndex = this.targetOffset;
let node = walker.nextNode();
for (let ii = viewFactories.length; behaviorIndex < ii; ++behaviorIndex) {
const factory = viewFactories[behaviorIndex];
const factoryIndex = factory.targetIndex;
while (node !== null) {
if (targetIndex === factoryIndex) {
behaviors[behaviorIndex] = factory.createBehavior(node);
break;
}
else {
node = walker.nextNode();
targetIndex++;
}
}
}
if (this.hasHostBehaviors) {
const hostFactories = this.hostBehaviorFactories;
for (let i = 0, ii = hostFactories.length; i < ii; ++i, ++behaviorIndex) {
behaviors[behaviorIndex] = hostFactories[i].createBehavior(hostBindingTarget);
}
}
return new HTMLView(fragment, behaviors);
}
/**
* Creates an HTMLView from this template, binds it to the source, and then appends it to the host.
* @param source - The data source to bind the template to.
* @param host - The Element where the template will be rendered.
* @param hostBindingTarget - An HTML element to target the host bindings at if different from the
* host that the template is being attached to.
*/
render(source, host, hostBindingTarget) {
if (typeof host === "string") {
host = document.getElementById(host);
}
if (hostBindingTarget === void 0) {
hostBindingTarget = host;
}
const view = this.create(hostBindingTarget);
view.bind(source, defaultExecutionContext);
view.appendTo(host);
return view;
}
}
// Much thanks to LitHTML for working this out!
const lastAttributeNameRegex =
/* eslint-disable-next-line no-control-regex */
/([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/;
/**
* Transforms a template literal string into a renderable ViewTemplate.
* @param strings - The string fragments that are interpolated with the values.
* @param values - The values that are interpolated with the string fragments.
* @remarks
* The html helper supports interpolation of strings, numbers, binding expressions,
* other template instances, and Directive instances.
* @public
*/
function html(strings, ...values) {
const directives = [];
let html = "";
for (let i = 0, ii = strings.length - 1; i < ii; ++i) {
const currentString = strings[i];
let value = values[i];
html += currentString;
if (value instanceof ViewTemplate) {
const template = value;
value = () => template;
}
if (typeof value === "function") {
value = new HTMLBindingDirective(value);
}
if (value instanceof TargetedHTMLDirective) {
const match = lastAttributeNameRegex.exec(currentString);
if (match !== null) {
value.targetName = match[2];
}
}
if (value instanceof HTMLDirective) {
// Since not all values are directives, we can't use i
// as the index for the placeholder. Instead, we need to
// use directives.length to get the next index.
html += value.createPlaceholder(directives.length);
directives.push(value);
}
else {
html += value;
}
}
html += strings[strings.length - 1];
return new ViewTemplate(html, directives);
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/ref.js
/**
* The runtime behavior for template references.
* @public
*/
class RefBehavior {
/**
* Creates an instance of RefBehavior.
* @param target - The element to reference.
* @param propertyName - The name of the property to assign the reference to.
*/
constructor(target, propertyName) {
this.target = target;
this.propertyName = propertyName;
}
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
*/
bind(source) {
source[this.propertyName] = this.target;
}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
*/
/* eslint-disable-next-line @typescript-eslint/no-empty-function */
unbind() { }
}
/**
* A directive that observes the updates a property with a reference to the element.
* @param propertyName - The name of the property to assign the reference to.
* @public
*/
function ref(propertyName) {
return new AttachedBehaviorHTMLDirective("fast-ref", RefBehavior, propertyName);
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/patterns/start-end.js
/**
* A mixin class implementing start and end elements.
* These are generally used to decorate text elements with icons or other visual indicators.
* @public
*/
class StartEnd {
handleStartContentChange() {
this.startContainer.classList.toggle("start", this.start.assignedNodes().length > 0);
}
handleEndContentChange() {
this.endContainer.classList.toggle("end", this.end.assignedNodes().length > 0);
}
}
/**
* The template for the end element.
* For use with {@link StartEnd}
*
* @public
*/
const endSlotTemplate = (context, definition) => html `
(definition.end ? "end" : void 0)}
>
x.handleEndContentChange()}">
${definition.end || ""}
`;
/**
* The template for the start element.
* For use with {@link StartEnd}
*
* @public
*/
const startSlotTemplate = (context, definition) => html `
x.handleStartContentChange()}"
>
${definition.start || ""}
`;
/**
* The template for the end element.
* For use with {@link StartEnd}
*
* @public
* @deprecated - use endSlotTemplate
*/
const endTemplate = html `
x.handleEndContentChange()}"
>
`;
/**
* The template for the start element.
* For use with {@link StartEnd}
*
* @public
* @deprecated - use startSlotTemplate
*/
const startTemplate = html `
x.handleStartContentChange()}"
>
`;
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/utilities/apply-mixins.js
/**
* Apply mixins to a constructor.
* Sourced from {@link https://www.typescriptlang.org/docs/handbook/mixins.html | TypeScript Documentation }.
* @public
*/
function applyMixins(derivedCtor, ...baseCtors) {
const derivedAttributes = AttributeConfiguration.locate(derivedCtor);
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== "constructor") {
Object.defineProperty(derivedCtor.prototype, name,
/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */
Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
}
});
const baseAttributes = AttributeConfiguration.locate(baseCtor);
baseAttributes.forEach(x => derivedAttributes.push(x));
});
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/accordion-item/accordion-item.js
/**
* An individual item in an {@link @microsoft/fast-foundation#(Accordion:class) }.
*
* @slot start - Content which can be provided between the heading and the icon
* @slot end - Content which can be provided between the start slot and icon
* @slot heading - Content which serves as the accordion item heading and text of the expand button
* @slot - The default slot for accordion item content
* @slot expanded-icon - The expanded icon
* @slot collapsed-icon - The collapsed icon
* @fires change - Fires a custom 'change' event when the button is invoked
* @csspart heading - Wraps the button
* @csspart button - The button which serves to invoke the item
* @csspart heading-content - Wraps the slot for the heading content within the button
* @csspart icon - The icon container
* @csspart expanded-icon - The expanded icon slot
* @csspart collapsed-icon - The collapsed icon
* @csspart region - The wrapper for the accordion item content
*
* @public
*/
class AccordionItem extends FoundationElement {
constructor() {
super(...arguments);
/**
* Configures the {@link https://www.w3.org/TR/wai-aria-1.1/#aria-level | level} of the
* heading element.
*
* @defaultValue 2
* @public
* @remarks
* HTML attribute: heading-level
*/
this.headinglevel = 2;
/**
* Expands or collapses the item.
*
* @public
* @remarks
* HTML attribute: expanded
*/
this.expanded = false;
/**
* @internal
*/
this.clickHandler = (e) => {
this.expanded = !this.expanded;
this.change();
};
this.change = () => {
this.$emit("change");
};
}
}
__decorate([
attr({
attribute: "heading-level",
mode: "fromView",
converter: nullableNumberConverter,
})
], AccordionItem.prototype, "headinglevel", void 0);
__decorate([
attr({ mode: "boolean" })
], AccordionItem.prototype, "expanded", void 0);
__decorate([
attr
], AccordionItem.prototype, "id", void 0);
applyMixins(AccordionItem, StartEnd);
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/accordion/accordion.js
/**
* Expand mode for {@link Accordion}
* @public
*/
const AccordionExpandMode = {
/**
* Designates only a single {@link @microsoft/fast-foundation#(AccordionItem:class) } can be open a time.
*/
single: "single",
/**
* Designates multiple {@link @microsoft/fast-foundation#(AccordionItem:class) | AccordionItems} can be open simultaneously.
*/
multi: "multi",
};
/**
* An Accordion Custom HTML Element
* Implements {@link https://www.w3.org/TR/wai-aria-practices-1.1/#accordion | ARIA Accordion}.
*
* @fires change - Fires a custom 'change' event when the active item changes
* @csspart item - The slot for the accordion items
* @public
*
* @remarks
* Designed to be used with {@link @microsoft/fast-foundation#accordionTemplate} and {@link @microsoft/fast-foundation#(AccordionItem:class)}.
*/
class Accordion extends FoundationElement {
constructor() {
super(...arguments);
/**
* Controls the expand mode of the Accordion, either allowing
* single or multiple item expansion.
* @public
*
* @remarks
* HTML attribute: expand-mode
*/
this.expandmode = AccordionExpandMode.multi;
this.activeItemIndex = 0;
this.change = () => {
this.$emit("change", this.activeid);
};
this.setItems = () => {
var _a;
if (this.accordionItems.length === 0) {
return;
}
this.accordionIds = this.getItemIds();
this.accordionItems.forEach((item, index) => {
if (item instanceof AccordionItem) {
item.addEventListener("change", this.activeItemChange);
if (this.isSingleExpandMode()) {
this.activeItemIndex !== index
? (item.expanded = false)
: (item.expanded = true);
}
}
const itemId = this.accordionIds[index];
item.setAttribute("id", typeof itemId !== "string" ? `accordion-${index + 1}` : itemId);
this.activeid = this.accordionIds[this.activeItemIndex];
item.addEventListener("keydown", this.handleItemKeyDown);
item.addEventListener("focus", this.handleItemFocus);
});
if (this.isSingleExpandMode()) {
const expandedItem = (_a = this.findExpandedItem()) !== null && _a !== void 0 ? _a : this.accordionItems[0];
expandedItem.setAttribute("aria-disabled", "true");
}
};
this.removeItemListeners = (oldValue) => {
oldValue.forEach((item, index) => {
item.removeEventListener("change", this.activeItemChange);
item.removeEventListener("keydown", this.handleItemKeyDown);
item.removeEventListener("focus", this.handleItemFocus);
});
};
this.activeItemChange = (event) => {
if (event.defaultPrevented || event.target !== event.currentTarget) {
return;
}
event.preventDefault();
const selectedItem = event.target;
this.activeid = selectedItem.getAttribute("id");
if (this.isSingleExpandMode()) {
this.resetItems();
selectedItem.expanded = true;
selectedItem.setAttribute("aria-disabled", "true");
this.accordionItems.forEach((item) => {
if (!item.hasAttribute("disabled") && item.id !== this.activeid) {
item.removeAttribute("aria-disabled");
}
});
}
this.activeItemIndex = Array.from(this.accordionItems).indexOf(selectedItem);
this.change();
};
this.handleItemKeyDown = (event) => {
// only handle the keydown if the event target is the accordion item
// prevents arrow keys from moving focus to accordion headers when focus is on accordion item panel content
if (event.target !== event.currentTarget) {
return;
}
this.accordionIds = this.getItemIds();
switch (event.key) {
case keyArrowUp:
event.preventDefault();
this.adjust(-1);
break;
case keyArrowDown:
event.preventDefault();
this.adjust(1);
break;
case keyHome:
this.activeItemIndex = 0;
this.focusItem();
break;
case keyEnd:
this.activeItemIndex = this.accordionItems.length - 1;
this.focusItem();
break;
}
};
this.handleItemFocus = (event) => {
// update the active item index if the focus moves to an accordion item via a different method other than the up and down arrow key actions
// only do so if the focus is actually on the accordion item and not on any of its children
if (event.target === event.currentTarget) {
const focusedItem = event.target;
const focusedIndex = (this.activeItemIndex = Array.from(this.accordionItems).indexOf(focusedItem));
if (this.activeItemIndex !== focusedIndex && focusedIndex !== -1) {
this.activeItemIndex = focusedIndex;
this.activeid = this.accordionIds[this.activeItemIndex];
}
}
};
}
/**
* @internal
*/
accordionItemsChanged(oldValue, newValue) {
if (this.$fastController.isConnected) {
this.removeItemListeners(oldValue);
this.setItems();
}
}
findExpandedItem() {
for (let item = 0; item < this.accordionItems.length; item++) {
if (this.accordionItems[item].getAttribute("expanded") === "true") {
return this.accordionItems[item];
}
}
return null;
}
resetItems() {
this.accordionItems.forEach((item, index) => {
item.expanded = false;
});
}
getItemIds() {
return this.accordionItems.map((accordionItem) => {
return accordionItem.getAttribute("id");
});
}
isSingleExpandMode() {
return this.expandmode === AccordionExpandMode.single;
}
adjust(adjustment) {
this.activeItemIndex = wrapInBounds(0, this.accordionItems.length - 1, this.activeItemIndex + adjustment);
this.focusItem();
}
focusItem() {
const element = this.accordionItems[this.activeItemIndex];
if (element instanceof AccordionItem) {
element.expandbutton.focus();
}
}
}
__decorate([
attr({ attribute: "expand-mode" })
], Accordion.prototype, "expandmode", void 0);
__decorate([
observable
], Accordion.prototype, "accordionItems", void 0);
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/node-observation.js
/**
* Creates a function that can be used to filter a Node array, selecting only elements.
* @param selector - An optional selector to restrict the filter to.
* @public
*/
function node_observation_elements(selector) {
if (selector) {
return function (value, index, array) {
return value.nodeType === 1 && value.matches(selector);
};
}
return function (value, index, array) {
return value.nodeType === 1;
};
}
/**
* A base class for node observation.
* @internal
*/
class NodeObservationBehavior {
/**
* Creates an instance of NodeObservationBehavior.
* @param target - The target to assign the nodes property on.
* @param options - The options to use in configuring node observation.
*/
constructor(target, options) {
this.target = target;
this.options = options;
this.source = null;
}
/**
* Bind this behavior to the source.
* @param source - The source to bind to.
* @param context - The execution context that the binding is operating within.
*/
bind(source) {
const name = this.options.property;
this.shouldUpdate = Observable.getAccessors(source).some((x) => x.name === name);
this.source = source;
this.updateTarget(this.computeNodes());
if (this.shouldUpdate) {
this.observe();
}
}
/**
* Unbinds this behavior from the source.
* @param source - The source to unbind from.
*/
unbind() {
this.updateTarget(emptyArray);
this.source = null;
if (this.shouldUpdate) {
this.disconnect();
}
}
/** @internal */
handleEvent() {
this.updateTarget(this.computeNodes());
}
computeNodes() {
let nodes = this.getNodes();
if (this.options.filter !== void 0) {
nodes = nodes.filter(this.options.filter);
}
return nodes;
}
updateTarget(value) {
this.source[this.options.property] = value;
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/templating/slotted.js
/**
* The runtime behavior for slotted node observation.
* @public
*/
class SlottedBehavior extends NodeObservationBehavior {
/**
* Creates an instance of SlottedBehavior.
* @param target - The slot element target to observe.
* @param options - The options to use when observing the slot.
*/
constructor(target, options) {
super(target, options);
}
/**
* Begins observation of the nodes.
*/
observe() {
this.target.addEventListener("slotchange", this);
}
/**
* Disconnects observation of the nodes.
*/
disconnect() {
this.target.removeEventListener("slotchange", this);
}
/**
* Retrieves the nodes that should be assigned to the target.
*/
getNodes() {
return this.target.assignedNodes(this.options);
}
}
/**
* A directive that observes the `assignedNodes()` of a slot and updates a property
* whenever they change.
* @param propertyOrOptions - The options used to configure slotted node observation.
* @public
*/
function slotted(propertyOrOptions) {
if (typeof propertyOrOptions === "string") {
propertyOrOptions = { property: propertyOrOptions };
}
return new AttachedBehaviorHTMLDirective("fast-slotted", SlottedBehavior, propertyOrOptions);
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/accordion/accordion.template.js
/**
* The template for the {@link @microsoft/fast-foundation#Accordion} component.
* @public
*/
const accordionTemplate = (context, definition) => /* TODO: deprecate slot name `item` to only support default slot https://github.com/microsoft/fast/issues/5515 */ html `
`;
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-element/dist/esm/styles/css.js
function collectStyles(strings, values) {
const styles = [];
let cssString = "";
const behaviors = [];
for (let i = 0, ii = strings.length - 1; i < ii; ++i) {
cssString += strings[i];
let value = values[i];
if (value instanceof CSSDirective) {
const behavior = value.createBehavior();
value = value.createCSS();
if (behavior) {
behaviors.push(behavior);
}
}
if (value instanceof ElementStyles || value instanceof CSSStyleSheet) {
if (cssString.trim() !== "") {
styles.push(cssString);
cssString = "";
}
styles.push(value);
}
else {
cssString += value;
}
}
cssString += strings[strings.length - 1];
if (cssString.trim() !== "") {
styles.push(cssString);
}
return {
styles,
behaviors,
};
}
/**
* Transforms a template literal string into styles.
* @param strings - The string fragments that are interpolated with the values.
* @param values - The values that are interpolated with the string fragments.
* @remarks
* The css helper supports interpolation of strings and ElementStyle instances.
* @public
*/
function css(strings, ...values) {
const { styles, behaviors } = collectStyles(strings, values);
const elementStyles = ElementStyles.create(styles);
if (behaviors.length) {
elementStyles.withBehaviors(...behaviors);
}
return elementStyles;
}
class CSSPartial extends CSSDirective {
constructor(styles, behaviors) {
super();
this.behaviors = behaviors;
this.css = "";
const stylesheets = styles.reduce((accumulated, current) => {
if (typeof current === "string") {
this.css += current;
}
else {
accumulated.push(current);
}
return accumulated;
}, []);
if (stylesheets.length) {
this.styles = ElementStyles.create(stylesheets);
}
}
createBehavior() {
return this;
}
createCSS() {
return this.css;
}
bind(el) {
if (this.styles) {
el.$fastController.addStyles(this.styles);
}
if (this.behaviors.length) {
el.$fastController.addBehaviors(this.behaviors);
}
}
unbind(el) {
if (this.styles) {
el.$fastController.removeStyles(this.styles);
}
if (this.behaviors.length) {
el.$fastController.removeBehaviors(this.behaviors);
}
}
}
/**
* Transforms a template literal string into partial CSS.
* @param strings - The string fragments that are interpolated with the values.
* @param values - The values that are interpolated with the string fragments.
* @public
*/
function cssPartial(strings, ...values) {
const { styles, behaviors } = collectStyles(strings, values);
return new CSSPartial(styles, behaviors);
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/utilities/style/display.js
/**
* A CSS fragment to set `display: none;` when the host is hidden using the [hidden] attribute.
* @public
*/
const display_hidden = `:host([hidden]){display:none}`;
/**
* Applies a CSS display property.
* Also adds CSS rules to not display the element when the [hidden] attribute is applied to the element.
* @param display - The CSS display property value
* @public
*/
function display(displayValue) {
return `${display_hidden}:host{display:${displayValue}}`;
}
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/accordion/accordion.styles.js
// Copyright (c) Jupyter Development Team.
// Copyright (c) Microsoft Corporation.
// Distributed under the terms of the Modified BSD License.
/**
* Styles for Accordion
* @public
*/
const accordionStyles = (context, definition) => css `
${display('flex')} :host {
box-sizing: border-box;
flex-direction: column;
font-family: ${bodyFont};
font-size: ${typeRampMinus1FontSize};
line-height: ${typeRampMinus1LineHeight};
color: ${neutralForegroundRest};
border-top: calc(${strokeWidth} * 1px) solid ${neutralStrokeDividerRest};
}
`;
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/accordion-item/accordion-item.template.js
/**
* The template for the {@link @microsoft/fast-foundation#(AccordionItem:class)} component.
* @public
*/
const accordionItemTemplate = (context, definition) => html `
`;
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/breadcrumb-item/breadcrumb-item.styles.js
// Copyright (c) Jupyter Development Team.
// Copyright (c) Microsoft Corporation.
// Distributed under the terms of the Modified BSD License.
/**
* Styles for Breadcrumb item
* @public
*/
const breadcrumbItemStyles = (context, definition) => css `
${display('inline-flex')} :host {
background: transparent;
box-sizing: border-box;
font-family: ${bodyFont};
font-size: ${typeRampBaseFontSize};
fill: currentColor;
line-height: ${typeRampBaseLineHeight};
min-width: calc(${heightNumber} * 1px);
outline: none;
color: ${neutralForegroundRest}
}
.listitem {
display: flex;
align-items: center;
width: max-content;
}
.separator {
margin: 0 6px;
display: flex;
}
.control {
align-items: center;
box-sizing: border-box;
color: ${accentForegroundRest};
cursor: pointer;
display: flex;
fill: inherit;
outline: none;
text-decoration: none;
white-space: nowrap;
}
.control:hover {
color: ${accentForegroundHover};
}
.control:active {
color: ${accentForegroundActive};
}
.control .content {
position: relative;
}
.control .content::before {
content: "";
display: block;
height: calc(${strokeWidth} * 1px);
left: 0;
position: absolute;
right: 0;
top: calc(1em + 4px);
width: 100%;
}
.control:hover .content::before {
background: ${accentForegroundHover};
}
.control:active .content::before {
background: ${accentForegroundActive};
}
.control:${focusVisible} .content::before {
background: ${accentForegroundFocus};
height: calc(${focusStrokeWidth} * 1px);
}
.control:not([href]) {
color: ${neutralForegroundRest};
cursor: default;
}
.control:not([href]) .content::before {
background: none;
}
.start,
.end {
display: flex;
}
::slotted(svg) {
/* TODO: adaptive typography https://github.com/microsoft/fast/issues/2432 */
width: 16px;
height: 16px;
}
.start {
margin-inline-end: 6px;
}
.end {
margin-inline-start: 6px;
}
`.withBehaviors(forcedColorsStylesheetBehavior(css `
.control:hover .content::before,
.control:${focusVisible} .content::before {
background: ${SystemColors.LinkText};
}
.start,
.end {
fill: ${SystemColors.ButtonText};
}
`));
;// CONCATENATED MODULE: ../node_modules/@jupyter/web-components/dist/esm/breadcrumb-item/index.js
// Copyright (c) Jupyter Development Team.
// Copyright (c) Microsoft Corporation.
// Distributed under the terms of the Modified BSD License.
/**
* Breadcrumb item class
*
* @public
* @tagname jp-breadcrumb-item
*/
class JupyterBreadcrumbItem extends BreadcrumbItem {
}
/**
* A function that returns a {@link @microsoft/fast-foundation#BreadcrumbItem} registration for configuring the component with a DesignSystem.
* Implements {@link @microsoft/fast-foundation#breadcrumbItemTemplate}
*
*
* @public
* @remarks
* Generates HTML Element: ``
*/
const jpBreadcrumbItem = JupyterBreadcrumbItem.compose({
baseName: 'breadcrumb-item',
baseClass: BreadcrumbItem,
template: breadcrumbItemTemplate,
styles: breadcrumbItemStyles,
separator: '/',
shadowOptions: {
delegatesFocus: true
}
});
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/form-associated/form-associated.js
const proxySlotName = "form-associated-proxy";
const ElementInternalsKey = "ElementInternals";
/**
* @alpha
*/
const supportsElementInternals = ElementInternalsKey in window &&
"setFormValue" in window[ElementInternalsKey].prototype;
const InternalsMap = new WeakMap();
/**
* Base function for providing Custom Element Form Association.
*
* @alpha
*/
function FormAssociated(BaseCtor) {
const C = class extends BaseCtor {
constructor(...args) {
super(...args);
/**
* Track whether the value has been changed from the initial value
*/
this.dirtyValue = false;
/**
* Sets the element's disabled state. A disabled element will not be included during form submission.
*
* @remarks
* HTML Attribute: disabled
*/
this.disabled = false;
/**
* These are events that are still fired by the proxy
* element based on user / programmatic interaction.
*
* The proxy implementation should be transparent to
* the app author, so block these events from emitting.
*/
this.proxyEventsToBlock = ["change", "click"];
this.proxyInitialized = false;
this.required = false;
this.initialValue = this.initialValue || "";
if (!this.elementInternals) {
// When elementInternals is not supported, formResetCallback is
// bound to an event listener, so ensure the handler's `this`
// context is correct.
this.formResetCallback = this.formResetCallback.bind(this);
}
}
/**
* Must evaluate to true to enable elementInternals.
* Feature detects API support and resolve respectively
*
* @internal
*/
static get formAssociated() {
return supportsElementInternals;
}
/**
* Returns the validity state of the element
*
* @alpha
*/
get validity() {
return this.elementInternals
? this.elementInternals.validity
: this.proxy.validity;
}
/**
* Retrieve a reference to the associated form.
* Returns null if not associated to any form.
*
* @alpha
*/
get form() {
return this.elementInternals ? this.elementInternals.form : this.proxy.form;
}
/**
* Retrieve the localized validation message,
* or custom validation message if set.
*
* @alpha
*/
get validationMessage() {
return this.elementInternals
? this.elementInternals.validationMessage
: this.proxy.validationMessage;
}
/**
* Whether the element will be validated when the
* form is submitted
*/
get willValidate() {
return this.elementInternals
? this.elementInternals.willValidate
: this.proxy.willValidate;
}
/**
* A reference to all associated label elements
*/
get labels() {
if (this.elementInternals) {
return Object.freeze(Array.from(this.elementInternals.labels));
}
else if (this.proxy instanceof HTMLElement &&
this.proxy.ownerDocument &&
this.id) {
// Labels associated by wrapping the element:
const parentLabels = this.proxy.labels;
// Labels associated using the `for` attribute
const forLabels = Array.from(this.proxy.getRootNode().querySelectorAll(`[for='${this.id}']`));
const labels = parentLabels
? forLabels.concat(Array.from(parentLabels))
: forLabels;
return Object.freeze(labels);
}
else {
return emptyArray;
}
}
/**
* Invoked when the `value` property changes
* @param previous - the previous value
* @param next - the new value
*
* @remarks
* If elements extending `FormAssociated` implement a `valueChanged` method
* They must be sure to invoke `super.valueChanged(previous, next)` to ensure
* proper functioning of `FormAssociated`
*/
valueChanged(previous, next) {
this.dirtyValue = true;
if (this.proxy instanceof HTMLElement) {
this.proxy.value = this.value;
}
this.currentValue = this.value;
this.setFormValue(this.value);
this.validate();
}
currentValueChanged() {
this.value = this.currentValue;
}
/**
* Invoked when the `initialValue` property changes
*
* @param previous - the previous value
* @param next - the new value
*
* @remarks
* If elements extending `FormAssociated` implement a `initialValueChanged` method
* They must be sure to invoke `super.initialValueChanged(previous, next)` to ensure
* proper functioning of `FormAssociated`
*/
initialValueChanged(previous, next) {
// If the value is clean and the component is connected to the DOM
// then set value equal to the attribute value.
if (!this.dirtyValue) {
this.value = this.initialValue;
this.dirtyValue = false;
}
}
/**
* Invoked when the `disabled` property changes
*
* @param previous - the previous value
* @param next - the new value
*
* @remarks
* If elements extending `FormAssociated` implement a `disabledChanged` method
* They must be sure to invoke `super.disabledChanged(previous, next)` to ensure
* proper functioning of `FormAssociated`
*/
disabledChanged(previous, next) {
if (this.proxy instanceof HTMLElement) {
this.proxy.disabled = this.disabled;
}
DOM.queueUpdate(() => this.classList.toggle("disabled", this.disabled));
}
/**
* Invoked when the `name` property changes
*
* @param previous - the previous value
* @param next - the new value
*
* @remarks
* If elements extending `FormAssociated` implement a `nameChanged` method
* They must be sure to invoke `super.nameChanged(previous, next)` to ensure
* proper functioning of `FormAssociated`
*/
nameChanged(previous, next) {
if (this.proxy instanceof HTMLElement) {
this.proxy.name = this.name;
}
}
/**
* Invoked when the `required` property changes
*
* @param previous - the previous value
* @param next - the new value
*
* @remarks
* If elements extending `FormAssociated` implement a `requiredChanged` method
* They must be sure to invoke `super.requiredChanged(previous, next)` to ensure
* proper functioning of `FormAssociated`
*/
requiredChanged(prev, next) {
if (this.proxy instanceof HTMLElement) {
this.proxy.required = this.required;
}
DOM.queueUpdate(() => this.classList.toggle("required", this.required));
this.validate();
}
/**
* The element internals object. Will only exist
* in browsers supporting the attachInternals API
*/
get elementInternals() {
if (!supportsElementInternals) {
return null;
}
let internals = InternalsMap.get(this);
if (!internals) {
internals = this.attachInternals();
InternalsMap.set(this, internals);
}
return internals;
}
/**
* @internal
*/
connectedCallback() {
super.connectedCallback();
this.addEventListener("keypress", this._keypressHandler);
if (!this.value) {
this.value = this.initialValue;
this.dirtyValue = false;
}
if (!this.elementInternals) {
this.attachProxy();
if (this.form) {
this.form.addEventListener("reset", this.formResetCallback);
}
}
}
/**
* @internal
*/
disconnectedCallback() {
super.disconnectedCallback();
this.proxyEventsToBlock.forEach(name => this.proxy.removeEventListener(name, this.stopPropagation));
if (!this.elementInternals && this.form) {
this.form.removeEventListener("reset", this.formResetCallback);
}
}
/**
* Return the current validity of the element.
*/
checkValidity() {
return this.elementInternals
? this.elementInternals.checkValidity()
: this.proxy.checkValidity();
}
/**
* Return the current validity of the element.
* If false, fires an invalid event at the element.
*/
reportValidity() {
return this.elementInternals
? this.elementInternals.reportValidity()
: this.proxy.reportValidity();
}
/**
* Set the validity of the control. In cases when the elementInternals object is not
* available (and the proxy element is used to report validity), this function will
* do nothing unless a message is provided, at which point the setCustomValidity method
* of the proxy element will be invoked with the provided message.
* @param flags - Validity flags
* @param message - Optional message to supply
* @param anchor - Optional element used by UA to display an interactive validation UI
*/
setValidity(flags, message, anchor) {
if (this.elementInternals) {
this.elementInternals.setValidity(flags, message, anchor);
}
else if (typeof message === "string") {
this.proxy.setCustomValidity(message);
}
}
/**
* Invoked when a connected component's form or fieldset has its disabled
* state changed.
* @param disabled - the disabled value of the form / fieldset
*/
formDisabledCallback(disabled) {
this.disabled = disabled;
}
formResetCallback() {
this.value = this.initialValue;
this.dirtyValue = false;
}
/**
* Attach the proxy element to the DOM
*/
attachProxy() {
var _a;
if (!this.proxyInitialized) {
this.proxyInitialized = true;
this.proxy.style.display = "none";
this.proxyEventsToBlock.forEach(name => this.proxy.addEventListener(name, this.stopPropagation));
// These are typically mapped to the proxy during
// property change callbacks, but during initialization
// on the initial call of the callback, the proxy is
// still undefined. We should find a better way to address this.
this.proxy.disabled = this.disabled;
this.proxy.required = this.required;
if (typeof this.name === "string") {
this.proxy.name = this.name;
}
if (typeof this.value === "string") {
this.proxy.value = this.value;
}
this.proxy.setAttribute("slot", proxySlotName);
this.proxySlot = document.createElement("slot");
this.proxySlot.setAttribute("name", proxySlotName);
}
(_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.appendChild(this.proxySlot);
this.appendChild(this.proxy);
}
/**
* Detach the proxy element from the DOM
*/
detachProxy() {
var _a;
this.removeChild(this.proxy);
(_a = this.shadowRoot) === null || _a === void 0 ? void 0 : _a.removeChild(this.proxySlot);
}
/** {@inheritDoc (FormAssociated:interface).validate} */
validate(anchor) {
if (this.proxy instanceof HTMLElement) {
this.setValidity(this.proxy.validity, this.proxy.validationMessage, anchor);
}
}
/**
* Associates the provided value (and optional state) with the parent form.
* @param value - The value to set
* @param state - The state object provided to during session restores and when autofilling.
*/
setFormValue(value, state) {
if (this.elementInternals) {
this.elementInternals.setFormValue(value, state || value);
}
}
_keypressHandler(e) {
switch (e.key) {
case keyEnter:
if (this.form instanceof HTMLFormElement) {
// Implicit submission
const defaultButton = this.form.querySelector("[type=submit]");
defaultButton === null || defaultButton === void 0 ? void 0 : defaultButton.click();
}
break;
}
}
/**
* Used to stop propagation of proxy element events
* @param e - Event object
*/
stopPropagation(e) {
e.stopPropagation();
}
};
attr({ mode: "boolean" })(C.prototype, "disabled");
attr({ mode: "fromView", attribute: "value" })(C.prototype, "initialValue");
attr({ attribute: "current-value" })(C.prototype, "currentValue");
attr(C.prototype, "name");
attr({ mode: "boolean" })(C.prototype, "required");
observable(C.prototype, "value");
return C;
}
/**
* @alpha
*/
function CheckableFormAssociated(BaseCtor) {
class C extends FormAssociated(BaseCtor) {
}
class D extends C {
constructor(...args) {
super(args);
/**
* Tracks whether the "checked" property has been changed.
* This is necessary to provide consistent behavior with
* normal input checkboxes
*/
this.dirtyChecked = false;
/**
* Provides the default checkedness of the input element
* Passed down to proxy
*
* @public
* @remarks
* HTML Attribute: checked
*/
this.checkedAttribute = false;
/**
* The checked state of the control.
*
* @public
*/
this.checked = false;
// Re-initialize dirtyChecked because initialization of other values
// causes it to become true
this.dirtyChecked = false;
}
checkedAttributeChanged() {
this.defaultChecked = this.checkedAttribute;
}
/**
* @internal
*/
defaultCheckedChanged() {
if (!this.dirtyChecked) {
// Setting this.checked will cause us to enter a dirty state,
// but if we are clean when defaultChecked is changed, we want to stay
// in a clean state, so reset this.dirtyChecked
this.checked = this.defaultChecked;
this.dirtyChecked = false;
}
}
checkedChanged(prev, next) {
if (!this.dirtyChecked) {
this.dirtyChecked = true;
}
this.currentChecked = this.checked;
this.updateForm();
if (this.proxy instanceof HTMLInputElement) {
this.proxy.checked = this.checked;
}
if (prev !== undefined) {
this.$emit("change");
}
this.validate();
}
currentCheckedChanged(prev, next) {
this.checked = this.currentChecked;
}
updateForm() {
const value = this.checked ? this.value : null;
this.setFormValue(value, value);
}
connectedCallback() {
super.connectedCallback();
this.updateForm();
}
formResetCallback() {
super.formResetCallback();
this.checked = !!this.checkedAttribute;
this.dirtyChecked = false;
}
}
attr({ attribute: "checked", mode: "boolean" })(D.prototype, "checkedAttribute");
attr({ attribute: "current-checked", converter: booleanConverter })(D.prototype, "currentChecked");
observable(D.prototype, "defaultChecked");
observable(D.prototype, "checked");
return D;
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/button/button.form-associated.js
class _Button extends FoundationElement {
}
/**
* A form-associated base class for the {@link @microsoft/fast-foundation#(Button:class)} component.
*
* @internal
*/
class FormAssociatedButton extends FormAssociated(_Button) {
constructor() {
super(...arguments);
this.proxy = document.createElement("input");
}
}
;// CONCATENATED MODULE: ../node_modules/@microsoft/fast-foundation/dist/esm/button/button.js
/**
* A Button Custom HTML Element.
* Based largely on the {@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button |