Skip to content

A Swiss Army knife for developers.

[DevToys 2.0] Added Split Grid component (#863)

Etienne BAUDOUX09ee685186f0
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridLength.cs b/src/app/dev/DevToys.Blazor/Components/GridLength.cs
similarity index 100%
rename from src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridLength.cs
rename to src/app/dev/DevToys.Blazor/Components/GridLength.cs
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridUnitType.cs b/src/app/dev/DevToys.Blazor/Components/GridUnitType.cs
similarity index 100%
rename from src/app/dev/DevToys.Blazor/Components/Layout/Grid/GridUnitType.cs
rename to src/app/dev/DevToys.Blazor/Components/GridUnitType.cs
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/Grid/Grid.razor.scss b/src/app/dev/DevToys.Blazor/Components/Layout/Grid/Grid.razor.scss
deleted file mode 100644
index e69de29bb..000000000
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor
new file mode 100644
index 000000000..ba6f34c80
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor
@@ -0,0 +1,24 @@
+@namespace DevToys.Blazor.Components
+@inherits JSStyledComponentBase
+
+<Container HorizontalAlignment="@HorizontalAlignment"
+ VerticalAlignment="@VerticalAlignment"
+ Width="@Width"
+ Height="@Height"
+ IsVisible="@IsVisible">
+ <div id="@Id"
+ @ref="@Element"
+ class="@FinalCssClasses"
+ style="@StyleValue"
+ @attributes="AdditionalAttributes">
+ <Container>
+ @LeftOrTopCellContent
+ </Container>
+ <div @ref="@_gutterElement" class="grid-split-gripper" style="@GutterStyle">
+ <FontIcon Glyph="@GripperGlyph" />
+ </div>
+ <Container>
+ @RightOrBottomCellContent
+ </Container>
+ </div>
+</Container>
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.cs b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.cs
new file mode 100644
index 000000000..a0d132b69
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.cs
@@ -0,0 +1,101 @@
+namespace DevToys.Blazor.Components;
+
+public partial class SplitGrid : JSStyledComponentBase
+{
+ protected override string JavaScriptFile => "./_content/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.js";
+
+ private ElementReference _gutterElement;
+
+ protected string? StyleValue => new StyleBuilder()
+ .AddStyle("display", "grid")
+ .AddStyle("grid-template-columns", $"{GetCellLength(LeftOrTopCellSize)} 16px {GetCellLength(RightOrBottomCellSize)}", GutterOrientation == Orientation.Vertical)
+ .AddStyle("grid-template-rows", $"{GetCellLength(LeftOrTopCellSize)} 16px {GetCellLength(RightOrBottomCellSize)}", GutterOrientation == Orientation.Horizontal)
+ .AddStyle(Style)
+ .Build();
+
+ protected string? GutterStyle => new StyleBuilder()
+ .AddStyle("cursor", "col-resize", GutterOrientation == Orientation.Vertical)
+ .AddStyle("cursor", "row-resize", GutterOrientation == Orientation.Horizontal)
+ .AddStyle("grid-column", "2", GutterOrientation == Orientation.Vertical)
+ .AddStyle("grid-column", "1/-1", GutterOrientation == Orientation.Horizontal)
+ .AddStyle("grid-row", "1/-1", GutterOrientation == Orientation.Vertical)
+ .AddStyle("grid-row", "2", GutterOrientation == Orientation.Horizontal)
+ .Build();
+
+ protected char GripperGlyph => GutterOrientation == Orientation.Vertical ? '\uE9F8' : '\uE9F5';
+
+ /// <summary>
+ /// Gets or sets the length of the left or top cell.
+ /// </summary>
+ [Parameter]
+ public GridLength LeftOrTopCellSize { get; set; } = new GridLength(1, GridUnitType.Fraction);
+
+ /// <summary>
+ /// Gets or sets the length of the right or bottom cell.
+ /// </summary>
+ [Parameter]
+ public GridLength RightOrBottomCellSize { get; set; } = new GridLength(1, GridUnitType.Fraction);
+
+ /// <summary>
+ /// Gets or sets the content to be rendered inside the component.
+ /// </summary>
+ [Parameter]
+ public RenderFragment? LeftOrTopCellContent { get; set; }
+
+ /// <summary>
+ /// Gets or sets the content to be rendered inside the component.
+ /// </summary>
+ [Parameter]
+ public RenderFragment? RightOrBottomCellContent { get; set; }
+
+ /// <summary>
+ /// Gets or set the orientation of the grid gutter.
+ /// </summary>
+ [Parameter]
+ public Orientation GutterOrientation { get; set; } = Orientation.Vertical;
+
+ /// <summary>
+ /// Gets or set the minimum size of the cells.
+ /// </summary>
+ [Parameter]
+ public int MinimumCellSize { get; set; }
+
+ public override async ValueTask DisposeAsync()
+ {
+ await (await JSModule).InvokeVoidAsync("dispose", Element);
+ await base.DisposeAsync();
+ }
+
+ protected override async Task OnAfterRenderAsync(bool firstRender)
+ {
+ await base.OnAfterRenderAsync(firstRender);
+
+ if (firstRender)
+ {
+ await (await JSModule).InvokeVoidAsync(
+ "initializeSplitGrid",
+ Element,
+ _gutterElement,
+ GutterOrientation == Orientation.Vertical,
+ MinimumCellSize);
+ }
+ }
+
+ private static string GetCellLength(GridLength length)
+ {
+ if (length.IsFraction)
+ {
+ return $"{length.Value}fr";
+ }
+ else if (length.IsAbsolute)
+ {
+ return length.Value.ToPx();
+ }
+ else
+ {
+ Guard.IsTrue(length.IsAuto);
+ ThrowHelper.ThrowNotSupportedException($"{nameof(GridLength)}.{nameof(GridLength.Auto)} is not supported in {nameof(SplitGrid)}.");
+ return string.Empty;
+ }
+ }
+}
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.js b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.js
new file mode 100644
index 000000000..7a2de205f
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.js
@@ -0,0 +1,64 @@
+// eslint-disable-next-line @typescript-eslint/triple-slash-reference
+///<reference path="../../../node_modules/split-grid/index.d.ts" />
+var __awaiter = (this && this.__awaiter) || function (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());
+ });
+};
+export function initializeSplitGrid(rootElement, gutter, vertical, minSize) {
+ return __awaiter(this, void 0, void 0, function* () {
+ yield loadSplitGridLibrary();
+ const windowSplitGrid = window;
+ let splitInstance;
+ if (vertical) {
+ splitInstance = windowSplitGrid.Split({
+ minSize: minSize,
+ snapOffset: 0,
+ columnGutters: [{
+ track: 1,
+ element: gutter,
+ }]
+ });
+ }
+ else {
+ splitInstance = windowSplitGrid.Split({
+ minSize: minSize,
+ snapOffset: 0,
+ rowGutters: [{
+ track: 1,
+ element: gutter,
+ }]
+ });
+ }
+ rootElement.splitInstance = splitInstance;
+ });
+}
+export function dispose(rootElement) {
+ if (rootElement.splitInstance) {
+ rootElement.splitInstance.destroy(true);
+ }
+}
+function loadSplitGridLibrary() {
+ return __awaiter(this, void 0, void 0, function* () {
+ const windowSplitGrid = window;
+ const loadLibraryTask = new Promise((resolve, reject) => {
+ // Load split-grid library, if needed.
+ if (!windowSplitGrid.Split) {
+ /* eslint-disable no-undef */
+ require(["_content/DevToys.Blazor/lib/split-grid/split-grid"], function (split) {
+ windowSplitGrid.Split = split;
+ resolve(null);
+ });
+ }
+ else {
+ resolve(null);
+ }
+ });
+ yield loadLibraryTask;
+ });
+}
+//# sourceMappingURL=SplitGrid.razor.js.map
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.scss b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.scss
new file mode 100644
index 000000000..2d198f578
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.scss
@@ -0,0 +1,5 @@
+.grid-split-gripper {
+ &:hover, &:active {
+ background-color: var(--subtle-fill-secondary);
+ }
+}
diff --git a/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.ts b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.ts
new file mode 100644
index 000000000..a426ed1f8
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/Components/Layout/SplitGrid/SplitGrid.razor.ts
@@ -0,0 +1,77 @@
+// eslint-disable-next-line @typescript-eslint/triple-slash-reference
+///<reference path="../../../node_modules/split-grid/index.d.ts" />
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+declare const require: any;
+
+import { SplitInstance, SplitOptions } from "split-grid";
+
+interface SplitHTMLElement extends HTMLElement {
+ splitInstance: SplitInstance;
+}
+
+interface WindowSplitGrid extends Window {
+ Split(options: SplitOptions): SplitInstance;
+}
+
+export async function initializeSplitGrid(
+ rootElement: SplitHTMLElement,
+ gutter: HTMLElement,
+ vertical: boolean,
+ minSize: number)
+ : Promise<any> {
+
+ await loadSplitGridLibrary();
+
+ const windowSplitGrid = window as unknown as WindowSplitGrid;
+ let splitInstance: SplitInstance;
+
+ if (vertical) {
+ splitInstance = windowSplitGrid.Split({
+ minSize: minSize,
+ snapOffset: 0,
+ columnGutters: [{
+ track: 1,
+ element: gutter,
+ }]
+ });
+ }
+ else {
+ splitInstance = windowSplitGrid.Split({
+ minSize: minSize,
+ snapOffset: 0,
+ rowGutters: [{
+ track: 1,
+ element: gutter,
+ }]
+ });
+ }
+
+ rootElement.splitInstance = splitInstance;
+}
+
+export function dispose(rootElement: SplitHTMLElement): void {
+ if (rootElement.splitInstance) {
+ rootElement.splitInstance.destroy(true);
+ }
+}
+
+async function loadSplitGridLibrary(): Promise<any> {
+ const windowSplitGrid = window as unknown as WindowSplitGrid;
+
+ const loadLibraryTask = new Promise((resolve, reject) => {
+ // Load split-grid library, if needed.
+ if (!windowSplitGrid.Split) {
+ /* eslint-disable no-undef */
+ require(["_content/DevToys.Blazor/lib/split-grid/split-grid"], function (split) {
+ windowSplitGrid.Split = split;
+ resolve(null);
+ });
+ }
+ else {
+ resolve(null);
+ }
+ });
+
+ await loadLibraryTask;
+}
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Blazor/Pages/Index.razor b/src/app/dev/DevToys.Blazor/Pages/Index.razor
index 573ecf0bf..1e18d4d4e 100644
--- a/src/app/dev/DevToys.Blazor/Pages/Index.razor
+++ b/src/app/dev/DevToys.Blazor/Pages/Index.razor
@@ -118,24 +118,30 @@
</GridCell>
<GridCell Column="1" ColumnSpan="2">
- <StackPanel Orientation="Orientation.Vertical">
- <TextBlock Appearance="TextBlockAppearance.TitleLarge" Text="@guiToolViewItem.ToolInstance.LongOrShortDisplayTitle" />
- <!-- TODO: Place here a component that takes in argument the guiToolViewItem -->
+ <SplitGrid>
+ <LeftOrTopCellContent>
+ <StackPanel Orientation="Orientation.Vertical">
+ <TextBlock Appearance="TextBlockAppearance.TitleLarge" Text="@guiToolViewItem.ToolInstance.LongOrShortDisplayTitle" />
+ <!-- TODO: Place here a component that takes in argument the guiToolViewItem -->
- <MonacoEditor />
- <Button VerticalAlignment="VerticalAlignment.Center" IsEnabled="true" @onclick="OnSetFavorite">Set favorite</Button>
- <Button HorizontalAlignment="HorizontalAlignment.Left" IsEnabled="false">Set favorite</Button>
- <Button HorizontalAlignment="HorizontalAlignment.Center" IsEnabled="true" Appearance="ButtonAppearance.Accent">Set favorite</Button>
- <Button HorizontalAlignment="HorizontalAlignment.Right" Height="100" Width="200" IsEnabled="false" Appearance="ButtonAppearance.Accent">Set favorite</Button>
- <Button IsEnabled="true" Appearance="ButtonAppearance.Stealth">Set favorite</Button>
- <Button VerticalAlignment="VerticalAlignment.Bottom" IsEnabled="false" Appearance="ButtonAppearance.Stealth">Set favorite</Button>
- <TextBox Header="First name" Placeholder="Normal" Style="margin-top: 12px; margin-left: 8px; margin-right: 8px;" />
- <TextBox Header="Middle name" Placeholder="Read only" IsReadOnly="true" Style="margin-top: 12px; margin-left: 8px; margin-right: 8px;" />
- <TextBox Header="Last name" Placeholder="Disabled" IsEnabled="false" Style="margin-top: 12px; margin-left: 8px; margin-right: 8px;" />
- <ProgressBar IsIndeterminate="true" Width="150" HorizontalAlignment="HorizontalAlignment.Left" />
- <ProgressBar Value="75" />
- <DropDownList Header="Drop down list header"
- Items="@(new List<DropDownListItem>
+ <MonacoEditor />
+ <Button VerticalAlignment="VerticalAlignment.Center" IsEnabled="true" @onclick="OnSetFavorite">Set favorite</Button>
+ <Button HorizontalAlignment="HorizontalAlignment.Left" IsEnabled="false">Set favorite</Button>
+ <Button HorizontalAlignment="HorizontalAlignment.Center" IsEnabled="true" Appearance="ButtonAppearance.Accent">Set favorite</Button>
+ <Button HorizontalAlignment="HorizontalAlignment.Right" Height="100" Width="200" IsEnabled="false" Appearance="ButtonAppearance.Accent">Set favorite</Button>
+ <Button IsEnabled="true" Appearance="ButtonAppearance.Stealth">Set favorite</Button>
+ <Button VerticalAlignment="VerticalAlignment.Bottom" IsEnabled="false" Appearance="ButtonAppearance.Stealth">Set favorite</Button>
+ <TextBox Header="First name" Placeholder="Normal" Style="margin-top: 12px; margin-left: 8px; margin-right: 8px;" />
+ <TextBox Header="Middle name" Placeholder="Read only" IsReadOnly="true" Style="margin-top: 12px; margin-left: 8px; margin-right: 8px;" />
+ <TextBox Header="Last name" Placeholder="Disabled" IsEnabled="false" Style="margin-top: 12px; margin-left: 8px; margin-right: 8px;" />
+ <ProgressBar IsIndeterminate="true" Width="150" HorizontalAlignment="HorizontalAlignment.Left" />
+ <ProgressBar Value="75" />
+ </StackPanel>
+ </LeftOrTopCellContent>
+ <RightOrBottomCellContent>
+ <StackPanel Orientation="Orientation.Vertical">
+ <DropDownList Header="Drop down list header"
+ Items="@(new List<DropDownListItem>
{
new DropDownListItem { Text = "Item 1", IconGlyph = '\uE670' },
new DropDownListItem { Text = "Item 2" },
@@ -153,33 +159,35 @@
new DropDownListItem { Text = "Item 14" },
new DropDownListItem { Text = "Item 15 - longer text" }
})">
- <TextBlock Appearance="TextBlockAppearance.Body" Text="Click me!" />
- </DropDownList>
- <ComboBox Items="@(new List<string>
- {
- "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10",
- "Item 11", "Item 12", "Item 13", "Item 14", "Item 15", "Item 16 - longer text"
- })"
- Context="item"
- @bind-SelectedIndex="@ComboBoxSelectedItem"
- Header="ComboBox header"
- HorizontalAlignment="HorizontalAlignment.Left">
- <ItemTemplate>
- @item
- </ItemTemplate>
- </ComboBox>
- <ListBox Items="@(new List<string>
- {
- "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10",
- "Item 11", "Item 12", "Item 13", "Item 14", "Item 15", "Item 16 - longer text"
- })"
- Context="item"
- SelectedIndex="1">
- <ItemTemplate>
- @item
- </ItemTemplate>
- </ListBox>
- </StackPanel>
+ <TextBlock Appearance="TextBlockAppearance.Body" Text="Click me!" />
+ </DropDownList>
+ <ComboBox Items="@(new List<string>
+ {
+ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10",
+ "Item 11", "Item 12", "Item 13", "Item 14", "Item 15", "Item 16 - longer text"
+ })"
+ Context="item"
+ @bind-SelectedIndex="@ComboBoxSelectedItem"
+ Header="ComboBox header"
+ HorizontalAlignment="HorizontalAlignment.Left">
+ <ItemTemplate>
+ @item
+ </ItemTemplate>
+ </ComboBox>
+ <ListBox Items="@(new List<string>
+ {
+ "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10",
+ "Item 11", "Item 12", "Item 13", "Item 14", "Item 15", "Item 16 - longer text"
+ })"
+ Context="item"
+ SelectedIndex="1">
+ <ItemTemplate>
+ @item
+ </ItemTemplate>
+ </ListBox>
+ </StackPanel>
+ </RightOrBottomCellContent>
+ </SplitGrid>
</GridCell>
</Grid>
</ScrollViewer>
diff --git a/src/app/dev/DevToys.Blazor/package.json b/src/app/dev/DevToys.Blazor/package.json
index 6222a30d4..590a7ffaf 100644
--- a/src/app/dev/DevToys.Blazor/package.json
+++ b/src/app/dev/DevToys.Blazor/package.json
@@ -29,6 +29,7 @@
"gulp-typescript": "^6.0.0-alpha.1",
"monaco-editor": "^0.39.0",
"sass": "^1.49.9",
+ "split-grid": "^1.0.11",
"ts-node": "^10.7.0",
"typescript": "^4.6.2",
"vinyl-buffer": "1.0.1",
diff --git a/src/app/dev/DevToys.Blazor/wwwroot/js/devtoys.js b/src/app/dev/DevToys.Blazor/wwwroot/js/devtoys.js
index 7124aeed0..5f282702b 100644
--- a/src/app/dev/DevToys.Blazor/wwwroot/js/devtoys.js
+++ b/src/app/dev/DevToys.Blazor/wwwroot/js/devtoys.js
@@ -1,47 +1 @@
-//var _dotNetObjRef;
-
-//window.blazorExtensions = {
-
-
-// toggleResizeTracking: function (dotNetObjRef) {
-// _dotNetObjRef = dotNetObjRef;
-
-// dotNetObjRef.invokeMethodAsync('ToggleResizeTracking').then(isResizeTrackingEnabled => {
-// if (isResizeTrackingEnabled) {
-// blazorExtensions.enableResizeTracking();
-// } else {
-// blazorExtensions.disableResizeTracking();
-// }
-// });
-// },
-// enableResizeTracking: function () {
-// console.log('enableResizeTracking invoked');
-// blazorExtensions.handleWindowResize();
-// window.addEventListener("resize", blazorExtensions.handleWindowResize);
-// },
-// disableResizeTracking: function () {
-// console.log('disableResizeTracking invoked');
-// window.removeEventListener("resize", blazorExtensions.handleWindowResize);
-// },
-// handleWindowResize: function () {
-// let currentState = window.getComputedStyle(document.body, ':before').content.replace(/\"/g, '');
-// _dotNetObjRef.invokeMethodAsync('OnWindowResize', currentState);
-// /*
-// _dotNetObjRef.invokeMethodAsync('IsNearWindowBottom', content.scrollTop(), content.height(), container.height())
-// .then(isNearWindowBottom => {
-// console.log('isNearWindowBottom: ' + isNearWindowBottom);
-// if (isNearWindowBottom) {
-// alert("You are NEAR the bottom!");
-// }
-// });
-
-// _dotNetObjRef.invokeMethodAsync('IsAtWindowBottom', content.scrollTop(), content.height(), container.height())
-// .then(isAtWindowBottom => {
-// console.log('isAtWindowBottom: ' + isAtWindowBottom);
-// if (isAtWindowBottom) {
-// alert("You are AT the bottom!");
-// }
-// });
-//*/
-// }
-//};
+
\ No newline at end of file
diff --git a/src/app/dev/DevToys.Blazor/wwwroot/lib/split-grid/split-grid.js b/src/app/dev/DevToys.Blazor/wwwroot/lib/split-grid/split-grid.js
new file mode 100644
index 000000000..912bb2a6b
--- /dev/null
+++ b/src/app/dev/DevToys.Blazor/wwwroot/lib/split-grid/split-grid.js
@@ -0,0 +1,698 @@
+/*! split-grid - v1.0.11 */
+
+(function (global, factory) {
+ typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() :
+ typeof define === "function" && define.amd ? define(factory) :
+ (global = typeof globalThis !== "undefined" ? globalThis : global || self, global.Split = factory());
+}(this, (function () {
+ "use strict";
+
+ var numeric = function (value, unit) { return Number(value.slice(0, -1 * unit.length)); };
+
+ var parseValue = function (value) {
+ if (value.endsWith("px")) { return { value: value, type: "px", numeric: numeric(value, "px") }; }
+ if (value.endsWith("fr")) { return { value: value, type: "fr", numeric: numeric(value, "fr") }; }
+ if (value.endsWith("%")) { return { value: value, type: "%", numeric: numeric(value, "%") }; }
+ if (value === "auto") { return { value: value, type: "auto" }; }
+ return null;
+ };
+
+ var parse = function (rule) { return rule.split(" ").map(parseValue); };
+
+ var getSizeAtTrack = function (index, tracks, gap, end) {
+ if (gap === void 0) { gap = 0; }
+ if (end === void 0) { end = false; }
+
+ var newIndex = end ? index + 1 : index;
+ var trackSum = tracks
+ .slice(0, newIndex)
+ .reduce(function (accum, value) { return accum + value.numeric; }, 0);
+ var gapSum = gap ? index * gap : 0;
+
+ return trackSum + gapSum;
+ };
+
+ var getStyles = function (rule, ownRules, matchedRules) {
+ return ownRules.concat(matchedRules)
+ .map(function (r) { return r.style[rule]; })
+ .filter(function (style) { return style !== undefined && style !== ""; });
+ };
+
+ var getGapValue = function (unit, size) {
+ if (size.endsWith(unit)) {
+ return Number(size.slice(0, -1 * unit.length));
+ }
+ return null;
+ };
+
+ var firstNonZero = function (tracks) {
+ // eslint-disable-next-line no-plusplus
+ for (var i = 0; i < tracks.length; i++) {
+ if (tracks[i].numeric > 0) {
+ return i;
+ }
+ }
+ return null;
+ };
+
+ var NOOP = function () { return false; };
+
+ var defaultWriteStyle = function (element, gridTemplateProp, style) {
+ // eslint-disable-next-line no-param-reassign
+ element.style[gridTemplateProp] = style;
+ };
+
+ var getOption = function (options, propName, def) {
+ var value = options[propName];
+ if (value !== undefined) {
+ return value;
+ }
+ return def;
+ };
+
+ function getMatchedCSSRules(el) {
+ var ref;
+
+ return (ref = [])
+ .concat.apply(
+ ref, Array.from(el.ownerDocument.styleSheets).map(function (s) {
+ var rules = [];
+
+ try {
+ rules = Array.from(s.cssRules || []);
+ } catch (e) {
+ // Ignore results on security error
+ }
+
+ return rules;
+ })
+ )
+ .filter(function (r) {
+ var matches = false;
+ try {
+ matches = el.matches(r.selectorText);
+ } catch (e) {
+ // Ignore matching erros
+ }
+
+ return matches;
+ });
+ }
+
+ var gridTemplatePropColumns = "grid-template-columns";
+ var gridTemplatePropRows = "grid-template-rows";
+
+ var Gutter = function Gutter(direction, options, parentOptions) {
+ this.direction = direction;
+ this.element = options.element;
+ this.track = options.track;
+
+ if (direction === "column") {
+ this.gridTemplateProp = gridTemplatePropColumns;
+ this.gridGapProp = "grid-column-gap";
+ this.cursor = getOption(
+ parentOptions,
+ "columnCursor",
+ getOption(parentOptions, "cursor", "col-resize")
+ );
+ this.snapOffset = getOption(
+ parentOptions,
+ "columnSnapOffset",
+ getOption(parentOptions, "snapOffset", 30)
+ );
+ this.dragInterval = getOption(
+ parentOptions,
+ "columnDragInterval",
+ getOption(parentOptions, "dragInterval", 1)
+ );
+ this.clientAxis = "clientX";
+ this.optionStyle = getOption(parentOptions, "gridTemplateColumns");
+ } else if (direction === "row") {
+ this.gridTemplateProp = gridTemplatePropRows;
+ this.gridGapProp = "grid-row-gap";
+ this.cursor = getOption(
+ parentOptions,
+ "rowCursor",
+ getOption(parentOptions, "cursor", "row-resize")
+ );
+ this.snapOffset = getOption(
+ parentOptions,
+ "rowSnapOffset",
+ getOption(parentOptions, "snapOffset", 30)
+ );
+ this.dragInterval = getOption(
+ parentOptions,
+ "rowDragInterval",
+ getOption(parentOptions, "dragInterval", 1)
+ );
+ this.clientAxis = "clientY";
+ this.optionStyle = getOption(parentOptions, "gridTemplateRows");
+ }
+
+ this.onDragStart = getOption(parentOptions, "onDragStart", NOOP);
+ this.onDragEnd = getOption(parentOptions, "onDragEnd", NOOP);
+ this.onDrag = getOption(parentOptions, "onDrag", NOOP);
+ this.writeStyle = getOption(
+ parentOptions,
+ "writeStyle",
+ defaultWriteStyle
+ );
+
+ this.startDragging = this.startDragging.bind(this);
+ this.stopDragging = this.stopDragging.bind(this);
+ this.drag = this.drag.bind(this);
+
+ this.minSizeStart = options.minSizeStart;
+ this.minSizeEnd = options.minSizeEnd;
+
+ if (options.element) {
+ this.element.addEventListener("mousedown", this.startDragging);
+ this.element.addEventListener("touchstart", this.startDragging);
+ }
+ };
+
+ Gutter.prototype.getDimensions = function getDimensions() {
+ var ref = this.grid.getBoundingClientRect();
+ var width = ref.width;
+ var height = ref.height;
+ var top = ref.top;
+ var bottom = ref.bottom;
+ var left = ref.left;
+ var right = ref.right;
+
+ if (this.direction === "column") {
+ this.start = top;
+ this.end = bottom;
+ this.size = height;
+ } else if (this.direction === "row") {
+ this.start = left;
+ this.end = right;
+ this.size = width;
+ }
+ };
+
+ Gutter.prototype.getSizeAtTrack = function getSizeAtTrack$1(track, end) {
+ return getSizeAtTrack(
+ track,
+ this.computedPixels,
+ this.computedGapPixels,
+ end
+ );
+ };
+
+ Gutter.prototype.getSizeOfTrack = function getSizeOfTrack(track) {
+ return this.computedPixels[track].numeric;
+ };
+
+ Gutter.prototype.getRawTracks = function getRawTracks() {
+ var tracks = getStyles(
+ this.gridTemplateProp,
+ [this.grid],
+ getMatchedCSSRules(this.grid)
+ );
+ if (!tracks.length) {
+ if (this.optionStyle) { return this.optionStyle; }
+
+ throw Error("Unable to determine grid template tracks from styles.");
+ }
+ return tracks[0];
+ };
+
+ Gutter.prototype.getGap = function getGap() {
+ var gap = getStyles(
+ this.gridGapProp,
+ [this.grid],
+ getMatchedCSSRules(this.grid)
+ );
+ if (!gap.length) {
+ return null;
+ }
+ return gap[0];
+ };
+
+ Gutter.prototype.getRawComputedTracks = function getRawComputedTracks() {
+ return window.getComputedStyle(this.grid)[this.gridTemplateProp];
+ };
+
+ Gutter.prototype.getRawComputedGap = function getRawComputedGap() {
+ return window.getComputedStyle(this.grid)[this.gridGapProp];
+ };
+
+ Gutter.prototype.setTracks = function setTracks(raw) {
+ this.tracks = raw.split(" ");
+ this.trackValues = parse(raw);
+ };
+
+ Gutter.prototype.setComputedTracks = function setComputedTracks(raw) {
+ this.computedTracks = raw.split(" ");
+ this.computedPixels = parse(raw);
+ };
+
+ Gutter.prototype.setGap = function setGap(raw) {
+ this.gap = raw;
+ };
+
+ Gutter.prototype.setComputedGap = function setComputedGap(raw) {
+ this.computedGap = raw;
+ this.computedGapPixels = getGapValue("px", this.computedGap) || 0;
+ };
+
+ Gutter.prototype.getMousePosition = function getMousePosition(e) {
+ if ("touches" in e) { return e.touches[0][this.clientAxis]; }
+ return e[this.clientAxis];
+ };
+
+ Gutter.prototype.startDragging = function startDragging(e) {
+ if ("button" in e && e.button !== 0) {
+ return;
+ }
+
+ // Don't actually drag the element. We emulate that in the drag function.
+ e.preventDefault();
+
+ if (this.element) {
+ this.grid = this.element.parentNode;
+ } else {
+ this.grid = e.target.parentNode;
+ }
+
+ this.getDimensions();
+ this.setTracks(this.getRawTracks());
+ this.setComputedTracks(this.getRawComputedTracks());
+ this.setGap(this.getGap());
+ this.setComputedGap(this.getRawComputedGap());
+
+ var trackPercentage = this.trackValues.filter(
+ function (track) { return track.type === "%"; }
+ );
+ var trackFr = this.trackValues.filter(function (track) { return track.type === "fr"; });
+
+ this.totalFrs = trackFr.length;
+
+ if (this.totalFrs) {
+ var track = firstNonZero(trackFr);
+
+ if (track !== null) {
+ this.frToPixels =
+ this.computedPixels[track].numeric / trackFr[track].numeric;
+ }
+ }
+
+ if (trackPercentage.length) {
+ var track$1 = firstNonZero(trackPercentage);
+
+ if (track$1 !== null) {
+ this.percentageToPixels =
+ this.computedPixels[track$1].numeric /
+ trackPercentage[track$1].numeric;
+ }
+ }
+
+ // get start of gutter track
+ var gutterStart = this.getSizeAtTrack(this.track, false) + this.start;
+ this.dragStartOffset = this.getMousePosition(e) - gutterStart;
+
+ this.aTrack = this.track - 1;
+
+ if (this.track < this.tracks.length - 1) {
+ this.bTrack = this.track + 1;
+ } else {
+ throw Error(
+ ("Invalid track index: " + (this.track) + ". Track must be between two other tracks and only " + (this.tracks.length) + " tracks were found.")
+ );
+ }
+
+ this.aTrackStart = this.getSizeAtTrack(this.aTrack, false) + this.start;
+ this.bTrackEnd = this.getSizeAtTrack(this.bTrack, true) + this.start;
+
+ // Set the dragging property of the pair object.
+ this.dragging = true;
+
+ // All the binding. `window` gets the stop events in case we drag out of the elements.
+ window.addEventListener("mouseup", this.stopDragging);
+ window.addEventListener("touchend", this.stopDragging);
+ window.addEventListener("touchcancel", this.stopDragging);
+ window.addEventListener("mousemove", this.drag);
+ window.addEventListener("touchmove", this.drag);
+
+ // Disable selection. Disable!
+ this.grid.addEventListener("selectstart", NOOP);
+ this.grid.addEventListener("dragstart", NOOP);
+
+ this.grid.style.userSelect = "none";
+ this.grid.style.webkitUserSelect = "none";
+ this.grid.style.MozUserSelect = "none";
+ this.grid.style.pointerEvents = "none";
+
+ // Set the cursor at multiple levels
+ this.grid.style.cursor = this.cursor;
+ window.document.body.style.cursor = this.cursor;
+
+ this.onDragStart(this.direction, this.track);
+ };
+
+ Gutter.prototype.stopDragging = function stopDragging() {
+ this.dragging = false;
+
+ // Remove the stored event listeners. This is why we store them.
+ this.cleanup();
+
+ this.onDragEnd(this.direction, this.track);
+
+ if (this.needsDestroy) {
+ if (this.element) {
+ this.element.removeEventListener(
+ "mousedown",
+ this.startDragging
+ );
+ this.element.removeEventListener(
+ "touchstart",
+ this.startDragging
+ );
+ }
+ this.destroyCb();
+ this.needsDestroy = false;
+ this.destroyCb = null;
+ }
+ };
+
+ Gutter.prototype.drag = function drag(e) {
+ var mousePosition = this.getMousePosition(e);
+
+ var gutterSize = this.getSizeOfTrack(this.track);
+ var minMousePosition =
+ this.aTrackStart +
+ this.minSizeStart +
+ this.dragStartOffset +
+ this.computedGapPixels;
+ var maxMousePosition =
+ this.bTrackEnd -
+ this.minSizeEnd -
+ this.computedGapPixels -
+ (gutterSize - this.dragStartOffset);
+ var minMousePositionOffset = minMousePosition + this.snapOffset;
+ var maxMousePositionOffset = maxMousePosition - this.snapOffset;
+
+ if (mousePosition < minMousePositionOffset) {
+ mousePosition = minMousePosition;
+ }
+
+ if (mousePosition > maxMousePositionOffset) {
+ mousePosition = maxMousePosition;
+ }
+
+ if (mousePosition < minMousePosition) {
+ mousePosition = minMousePosition;
+ } else if (mousePosition > maxMousePosition) {
+ mousePosition = maxMousePosition;
+ }
+
+ var aTrackSize =
+ mousePosition -
+ this.aTrackStart -
+ this.dragStartOffset -
+ this.computedGapPixels;
+ var bTrackSize =
+ this.bTrackEnd -
+ mousePosition +
+ this.dragStartOffset -
+ gutterSize -
+ this.computedGapPixels;
+
+ if (this.dragInterval > 1) {
+ var aTrackSizeIntervaled =
+ Math.round(aTrackSize / this.dragInterval) * this.dragInterval;
+ bTrackSize -= aTrackSizeIntervaled - aTrackSize;
+ aTrackSize = aTrackSizeIntervaled;
+ }
+
+ if (aTrackSize < this.minSizeStart) {
+ aTrackSize = this.minSizeStart;
+ }
+
+ if (bTrackSize < this.minSizeEnd) {
+ bTrackSize = this.minSizeEnd;
+ }
+
+ if (this.trackValues[this.aTrack].type === "px") {
+ this.tracks[this.aTrack] = aTrackSize + "px";
+ } else if (this.trackValues[this.aTrack].type === "fr") {
+ if (this.totalFrs === 1) {
+ this.tracks[this.aTrack] = "1fr";
+ } else {
+ var targetFr = aTrackSize / this.frToPixels;
+ this.tracks[this.aTrack] = targetFr + "fr";
+ }
+ } else if (this.trackValues[this.aTrack].type === "%") {
+ var targetPercentage = aTrackSize / this.percentageToPixels;
+ this.tracks[this.aTrack] = targetPercentage + "%";
+ }
+
+ if (this.trackValues[this.bTrack].type === "px") {
+ this.tracks[this.bTrack] = bTrackSize + "px";
+ } else if (this.trackValues[this.bTrack].type === "fr") {
+ if (this.totalFrs === 1) {
+ this.tracks[this.bTrack] = "1fr";
+ } else {
+ var targetFr$1 = bTrackSize / this.frToPixels;
+ this.tracks[this.bTrack] = targetFr$1 + "fr";
+ }
+ } else if (this.trackValues[this.bTrack].type === "%") {
+ var targetPercentage$1 = bTrackSize / this.percentageToPixels;
+ this.tracks[this.bTrack] = targetPercentage$1 + "%";
+ }
+
+ var style = this.tracks.join(" ");
+ this.writeStyle(this.grid, this.gridTemplateProp, style);
+ this.onDrag(this.direction, this.track, style);
+ };
+
+ Gutter.prototype.cleanup = function cleanup() {
+ window.removeEventListener("mouseup", this.stopDragging);
+ window.removeEventListener("touchend", this.stopDragging);
+ window.removeEventListener("touchcancel", this.stopDragging);
+ window.removeEventListener("mousemove", this.drag);
+ window.removeEventListener("touchmove", this.drag);
+
+ if (this.grid) {
+ this.grid.removeEventListener("selectstart", NOOP);
+ this.grid.removeEventListener("dragstart", NOOP);
+
+ this.grid.style.userSelect = "";
+ this.grid.style.webkitUserSelect = "";
+ this.grid.style.MozUserSelect = "";
+ this.grid.style.pointerEvents = "";
+
+ this.grid.style.cursor = "";
+ }
+
+ window.document.body.style.cursor = "";
+ };
+
+ Gutter.prototype.destroy = function destroy(immediate, cb) {
+ if (immediate === void 0) immediate = true;
+
+ if (immediate || this.dragging === false) {
+ this.cleanup();
+ if (this.element) {
+ this.element.removeEventListener(
+ "mousedown",
+ this.startDragging
+ );
+ this.element.removeEventListener(
+ "touchstart",
+ this.startDragging
+ );
+ }
+
+ if (cb) {
+ cb();
+ }
+ } else {
+ this.needsDestroy = true;
+ if (cb) {
+ this.destroyCb = cb;
+ }
+ }
+ };
+
+ var getTrackOption = function (options, track, defaultValue) {
+ if (track in options) {
+ return options[track];
+ }
+
+ return defaultValue;
+ };
+
+ var createGutter = function (direction, options) {
+ return function (gutterOptions) {
+ if (gutterOptions.track < 1) {
+ throw Error(
+ ("Invalid track index: " + (gutterOptions.track) + ". Track must be between two other tracks.")
+ );
+ }
+
+ var trackMinSizes =
+ direction === "column"
+ ? options.columnMinSizes || {}
+ : options.rowMinSizes || {};
+ var trackMinSize = direction === "column" ? "columnMinSize" : "rowMinSize";
+
+ return new Gutter(
+ direction,
+ Object.assign({}, {
+ minSizeStart: getTrackOption(
+ trackMinSizes,
+ gutterOptions.track - 1,
+ getOption(
+ options,
+ trackMinSize,
+ getOption(options, "minSize", 0)
+ )
+ ),
+ minSizeEnd: getTrackOption(
+ trackMinSizes,
+ gutterOptions.track + 1,
+ getOption(
+ options,
+ trackMinSize,
+ getOption(options, "minSize", 0)
+ )
+ )
+ },
+ gutterOptions),
+ options
+ );
+ };
+ };
+
+ var Grid = function Grid(options) {
+ var this$1 = this;
+
+ this.columnGutters = {};
+ this.rowGutters = {};
+
+ this.options = Object.assign({}, {
+ columnGutters: options.columnGutters || [],
+ rowGutters: options.rowGutters || [],
+ columnMinSizes: options.columnMinSizes || {},
+ rowMinSizes: options.rowMinSizes || {}
+ },
+ options);
+
+ this.options.columnGutters.forEach(function (gutterOptions) {
+ this$1.columnGutters[gutterOptions.track] = createGutter(
+ "column",
+ this$1.options
+ )(gutterOptions);
+ });
+
+ this.options.rowGutters.forEach(function (gutterOptions) {
+ this$1.rowGutters[gutterOptions.track] = createGutter(
+ "row",
+ this$1.options
+ )(gutterOptions);
+ });
+ };
+
+ Grid.prototype.addColumnGutter = function addColumnGutter(element, track) {
+ if (this.columnGutters[track]) {
+ this.columnGutters[track].destroy();
+ }
+
+ this.columnGutters[track] = createGutter(
+ "column",
+ this.options
+ )({
+ element: element,
+ track: track,
+ });
+ };
+
+ Grid.prototype.addRowGutter = function addRowGutter(element, track) {
+ if (this.rowGutters[track]) {
+ this.rowGutters[track].destroy();
+ }
+
+ this.rowGutters[track] = createGutter(
+ "row",
+ this.options
+ )({
+ element: element,
+ track: track,
+ });
+ };
+
+ Grid.prototype.removeColumnGutter = function removeColumnGutter(track, immediate) {
+ var this$1 = this;
+ if (immediate === void 0) immediate = true;
+
+ if (this.columnGutters[track]) {
+ this.columnGutters[track].destroy(immediate, function () {
+ delete this$1.columnGutters[track];
+ });
+ }
+ };
+
+ Grid.prototype.removeRowGutter = function removeRowGutter(track, immediate) {
+ var this$1 = this;
+ if (immediate === void 0) immediate = true;
+
+ if (this.rowGutters[track]) {
+ this.rowGutters[track].destroy(immediate, function () {
+ delete this$1.rowGutters[track];
+ });
+ }
+ };
+
+ Grid.prototype.handleDragStart = function handleDragStart(e, direction, track) {
+ if (direction === "column") {
+ if (this.columnGutters[track]) {
+ this.columnGutters[track].destroy();
+ }
+
+ this.columnGutters[track] = createGutter(
+ "column",
+ this.options
+ )({
+ track: track,
+ });
+ this.columnGutters[track].startDragging(e);
+ } else if (direction === "row") {
+ if (this.rowGutters[track]) {
+ this.rowGutters[track].destroy();
+ }
+
+ this.rowGutters[track] = createGutter(
+ "row",
+ this.options
+ )({
+ track: track,
+ });
+ this.rowGutters[track].startDragging(e);
+ }
+ };
+
+ Grid.prototype.destroy = function destroy(immediate) {
+ var this$1 = this;
+ if (immediate === void 0) immediate = true;
+
+ Object.keys(this.columnGutters).forEach(function (track) {
+ return this$1.columnGutters[track].destroy(immediate, function () {
+ delete this$1.columnGutters[track];
+ });
+ }
+ );
+ Object.keys(this.rowGutters).forEach(function (track) {
+ return this$1.rowGutters[track].destroy(immediate, function () {
+ delete this$1.rowGutters[track];
+ });
+ }
+ );
+ };
+
+ function index(options) { return new Grid(options); }
+
+ return index;
+
+})));
\ No newline at end of file