Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10064250
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> fix packageid <DFF> @@ -4,6 +4,7 @@ <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> + <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup>
1
fix packageid
0
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10064251
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> fix packageid <DFF> @@ -4,6 +4,7 @@ <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> + <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup>
1
fix packageid
0
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10064252
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> fix packageid <DFF> @@ -4,6 +4,7 @@ <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> + <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup>
1
fix packageid
0
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10064253
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> fix packageid <DFF> @@ -4,6 +4,7 @@ <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> + <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup>
1
fix packageid
0
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10064254
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> fix packageid <DFF> @@ -4,6 +4,7 @@ <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> + <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup>
1
fix packageid
0
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10064255
<NME> AvaloniaEdit.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> </PropertyGroup> <ItemGroup> <AvaloniaResource Include="**\*.xaml;Assets\*;" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" /> </ItemGroup> <ItemGroup> <None Remove="Search\Assets\CaseSensitive.png" /> <None Remove="Search\Assets\CompleteWord.png" /> <None Remove="Search\Assets\FindNext.png" /> <None Remove="Search\Assets\FindPrevious.png" /> <None Remove="Search\Assets\RegularExpression.png" /> <None Remove="Search\Assets\ReplaceAll.png" /> <None Remove="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Search\Assets\CaseSensitive.png" /> <EmbeddedResource Include="Search\Assets\CompleteWord.png" /> <EmbeddedResource Include="Search\Assets\FindNext.png" /> <EmbeddedResource Include="Search\Assets\FindPrevious.png" /> <EmbeddedResource Include="Search\Assets\RegularExpression.png" /> <EmbeddedResource Include="Search\Assets\ReplaceAll.png" /> <EmbeddedResource Include="Search\Assets\ReplaceNext.png" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="System.Collections.Immutable" Version="1.6.0" /> </ItemGroup> <ItemGroup> <Compile Update="SR.Designer.cs"> <DesignTime>True</DesignTime> <AutoGen>True</AutoGen> <DependentUpon>SR.resx</DependentUpon> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Update="SR.resx"> <Generator>PublicResXFileCodeGenerator</Generator> <LastGenOutput>SR.Designer.cs</LastGenOutput> </EmbeddedResource> </ItemGroup> <Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences"> <ItemGroup> <ReferencePath Condition="'%(FileName)' == 'Splat'"> <Aliases>SystemDrawing</Aliases> </ReferencePath> </ItemGroup> </Target> </Project> <MSG> fix packageid <DFF> @@ -4,6 +4,7 @@ <TargetFramework>netstandard2.0</TargetFramework> <WarningsNotAsErrors>0612,0618</WarningsNotAsErrors> <Version>$(AvaloniaVersion)</Version> + <PackageId>Avalonia.AvaloniaEdit</PackageId> </PropertyGroup> <ItemGroup>
1
fix packageid
0
.csproj
csproj
mit
AvaloniaUI/AvaloniaEdit
10064256
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); } } ], $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function() { rowClickArgs = arguments; } }, grid = new Grid($element, gridOptions).render() .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); ok(rowClickArgs[0] instanceof jQuery.Event, "jQuery event arg"); equal(rowClickArgs[1], this.testData[1], "item arg"); equal(rowClickArgs[2], 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseover." + JSGRID, $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseover adds selectedRowClass"); $secondRow.trigger("mouseout." + JSGRID, $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseout removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Grid core refactoring <DFF> @@ -470,7 +470,7 @@ $(function() { .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); - $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); + $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); @@ -480,19 +480,19 @@ $(function() { $element = $("#jsGrid"), $secondRow, gridOptions = { - rowClick: function() { - rowClickArgs = arguments; + rowClick: function(args) { + rowClickArgs = args; } }, grid = new Grid($element, gridOptions).render() .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); - $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); + $secondRow.trigger("click", $.Event($secondRow)); -
11
Core: Grid core refactoring
11
.js
tests
mit
tabalinas/jsgrid
10064257
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); } } ], $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function() { rowClickArgs = arguments; } }, grid = new Grid($element, gridOptions).render() .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); ok(rowClickArgs[0] instanceof jQuery.Event, "jQuery event arg"); equal(rowClickArgs[1], this.testData[1], "item arg"); equal(rowClickArgs[2], 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseover." + JSGRID, $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseover adds selectedRowClass"); $secondRow.trigger("mouseout." + JSGRID, $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseout removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Grid core refactoring <DFF> @@ -470,7 +470,7 @@ $(function() { .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); - $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); + $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); @@ -480,19 +480,19 @@ $(function() { $element = $("#jsGrid"), $secondRow, gridOptions = { - rowClick: function() { - rowClickArgs = arguments; + rowClick: function(args) { + rowClickArgs = args; } }, grid = new Grid($element, gridOptions).render() .option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); - $secondRow.trigger("click." + JSGRID, $.Event($secondRow)); + $secondRow.trigger("click", $.Event($secondRow)); -
11
Core: Grid core refactoring
11
.js
tests
mit
tabalinas/jsgrid
10064258
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064259
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064260
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064261
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064262
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064263
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064264
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064265
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064266
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064267
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064268
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064269
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064270
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064271
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064272
<NME> FormattedTextElement.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Avalonia; using Avalonia.Media; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Utils; using JetBrains.Annotations; namespace AvaloniaEdit.Rendering { /// <summary> /// Formatted text (not normal document text). /// This is used as base class for various VisualLineElements that are displayed using a /// FormattedText, for example newline markers or collapsed folding sections. /// </summary> public class FormattedTextElement : VisualLineElement { internal readonly FormattedText FormattedText; internal string Text; internal TextLine TextLine; /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(string text, int documentLength) : base(1, documentLength) { Text = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(TextLine text, int documentLength) : base(1, documentLength) { TextLine = text ?? throw new ArgumentNullException(nameof(text)); } /// <summary> /// Creates a new FormattedTextElement that displays the specified text /// and occupies the specified length in the document. /// </summary> public FormattedTextElement(FormattedText text, int documentLength) : base(1, documentLength) { FormattedText = text ?? throw new ArgumentNullException(nameof(text)); } /// <inheritdoc/> public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { if (TextLine == null) { var formatter = TextFormatterFactory.Create(context.TextView); TextLine = PrepareText(formatter, Text, TextRunProperties); Text = null; } return new FormattedTextRun(this, TextRunProperties); } /// <summary> /// Constructs a TextLine from a simple text. /// </summary> public static TextLine PrepareText(TextFormatter formatter, string text, TextRunProperties properties) { if (formatter == null) throw new ArgumentNullException(nameof(formatter)); if (text == null) throw new ArgumentNullException(nameof(text)); if (properties == null) throw new ArgumentNullException(nameof(properties)); return formatter.FormatLine( new SimpleTextSource(text, properties), 0, 32000, new VisualLineTextParagraphProperties { defaultTextRunProperties = properties, textWrapping = TextWrapping.NoWrap, tabSize = 40 }); } } /// <summary> /// This is the TextRun implementation used by the <see cref="FormattedTextElement"/> class. /// </summary> public class FormattedTextRun : DrawableTextRun { /// <summary> /// Creates a new FormattedTextRun. /// </summary> public FormattedTextRun(FormattedTextElement element, TextRunProperties properties) { if (properties == null) throw new ArgumentNullException(nameof(properties)); Properties = properties; Element = element ?? throw new ArgumentNullException(nameof(element)); } /// <summary> /// Gets the element for which the FormattedTextRun was created. /// </summary> public FormattedTextElement Element { get; } public override ReadOnlySlice<char> Text { get; } /// <inheritdoc/> public override TextRunProperties Properties { get; } public override double Baseline => Element.FormattedText?.Baseline ?? Element.TextLine.Baseline; /// <inheritdoc/> public override Size Size { get { var formattedText = Element.FormattedText; if (formattedText != null) { return formattedText.Measure(); } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace, return new Size(text.WidthIncludingTrailingWhitespace, text.Height); } } /// <inheritdoc/> public override void Draw(DrawingContext drawingContext, Point origin) { if (Element.FormattedText != null) { //var y = origin.Y - Element.FormattedText.Baseline; drawingContext.DrawText(Element.FormattedText, origin); } else { //var y = origin.Y - Element.TextLine.Baseline; Element.TextLine.Draw(drawingContext, origin); } } } } <MSG> Update to latest Avalonia beta <DFF> @@ -134,7 +134,7 @@ namespace AvaloniaEdit.Rendering var formattedText = Element.FormattedText; if (formattedText != null) { - return formattedText.Measure(); + return formattedText.Bounds.Size; } var text = Element.TextLine; return new Size(text.WidthIncludingTrailingWhitespace,
1
Update to latest Avalonia beta
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064273
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); done(); } }); }); it('should bypass insertion if before returns `false`', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', scripts = document.querySelectorAll(selector); if (scripts.length === 2) done(); }, numRetries: 1 }); }); // Un-'x' this for testing ad blocked scripts. // Ghostery: Disallow "Google Adservices" // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a // custom filter under Options // xit('it should report ad blocked scripts as missing', function(done) { var s1 = 'https://www.googletagservices.com/tag/js/gpt.js', s2 = 'https://munchkin.marketo.net/munchkin-beta.js'; loadjs([s1, s2, 'assets/file1.js'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // verify image was loaded if (img.src === src) assert.equal(img.naturalWidth > 0, true); }); } function assertNotLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // fail if image was loaded if (img.src === src) assert.equal(img.naturalWidth, 0); }); } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with anchor tags', function(done) { var src = 'assets/flash.png#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); it('should support mix of img and js', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src, 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> added image file extension tests, bumped version number <DFF> @@ -426,6 +426,22 @@ describe('LoadJS tests', function() { }); + it('detects png|gif|jpg|svg|webp extensions', function(done) { + let files = [ + 'assets/flash.png', + 'assets/flash.gif', + 'assets/flash.jpg', + 'assets/flash.svg', + 'assets/flash.webp' + ]; + + loadjs(files, function() { + files.forEach(file => {assertLoaded(file);}); + done(); + }); + }); + + it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random();
16
added image file extension tests, bumped version number
0
.js
js
mit
muicss/loadjs
10064274
<NME> tests.js <BEF> /** * loadjs tests * @module test/tests.js */ var pathsLoaded = null, // file register testEl = null, assert = chai.assert, expect = chai.expect; describe('LoadJS tests', function() { beforeEach(function() { // reset register pathsLoaded = {}; // reset loadjs dependencies loadjs.reset(); }); // ========================================================================== // JavaScript file loading tests // ========================================================================== describe('JavaScript file loading tests', function() { it('should call success callback on valid path', function(done) { loadjs(['assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); done(); } }); }); it('should call error callback on invalid path', function(done) { loadjs(['assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should call before callback before embedding into document', function(done) { var scriptTags = []; loadjs(['assets/file1.js', 'assets/file2.js'], { before: function(path, el) { scriptTags.push({ path: path, el: el }); // add cross origin script for file2 if (path === 'assets/file2.js') { el.crossOrigin = 'anonymous'; } }, success: function() { assert.equal(scriptTags[0].path, 'assets/file1.js'); assert.equal(scriptTags[1].path, 'assets/file2.js'); assert.equal(scriptTags[0].el.crossOrigin, undefined); assert.equal(scriptTags[1].el.crossOrigin, 'anonymous'); done(); } }); }); it('should bypass insertion if before returns `false`', function(done) { loadjs(['assets/file1.js'], { before: function(path, el) { // append to body (instead of head) document.body.appendChild(el); // return `false` to bypass default DOM insertion return false; }, success: function() { assert.equal(pathsLoaded['file1.js'], true); // verify that file was added to body var els = document.body.querySelectorAll('script'), el; for (var i=0; i < els.length; i++) { el = els[i]; if (el.src.indexOf('assets/file1.js') !== -1) done(); } } }); }); it('should call success callback on two valid paths', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], { success: function() { throw "Executed success callback"; }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } }); }); it('should support async false', function(done) { this.timeout(5000); var numCompleted = 0, numTests = 20, paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js']; // run tests sequentially var testFn = function(paths) { // add cache busters var pathsUncached = paths.slice(0); pathsUncached[0] += '?_=' + Math.random(); pathsUncached[1] += '?_=' + Math.random(); loadjs(pathsUncached, { success: function() { var f1 = paths[0].replace('assets/', ''); var f2 = paths[1].replace('assets/', ''); // check load order assert.isTrue(pathsLoaded[f1]); assert.isFalse(pathsLoaded[f2]); // increment tests numCompleted += 1; if (numCompleted === numTests) { // exit done(); } else { // reset register pathsLoaded = {}; // run test again paths.reverse(); testFn(paths); } }, async: false }); }; // run tests testFn(paths); }); it('should support multiple tries', function(done) { loadjs('assets/file-numretries.js', { error: function() { // check number of scripts in document var selector = 'script[src="assets/file-numretries.js"]', scripts = document.querySelectorAll(selector); if (scripts.length === 2) done(); }, numRetries: 1 }); }); // Un-'x' this for testing ad blocked scripts. // Ghostery: Disallow "Google Adservices" // AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a // custom filter under Options // xit('it should report ad blocked scripts as missing', function(done) { var s1 = 'https://www.googletagservices.com/tag/js/gpt.js', s2 = 'https://munchkin.marketo.net/munchkin-beta.js'; loadjs([s1, s2, 'assets/file1.js'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsNotFound.length, 2); assert.equal(pathsNotFound[0], s1); assert.equal(pathsNotFound[1], s2); done(); } }); }); }); // ========================================================================== // CSS file loading tests // ========================================================================== describe('CSS file loading tests', function() { before(function() { // add test div to body for css tests testEl = document.createElement('div'); testEl.className = 'test-div mui-container'; testEl.style.display = 'inline-block'; document.body.appendChild(testEl); }); afterEach(function() { var els = document.getElementsByTagName('link'), i = els.length, el; // iteratete through stylesheets while (i--) { el = els[i]; // remove test stylesheets if (el.href.indexOf('mocha.css') === -1) { el.parentNode.removeChild(el); } } }); it('should load one file', function(done) { loadjs(['assets/file1.css'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/file1.css', 'assets/file2.css'], { success: function() { assert.equal(testEl.offsetWidth, 200); done(); } }); }); it('should call error callback on one invalid path', function(done) { loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(testEl.offsetWidth, 100); assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css'); done(); } }); }); it('should support mix of css and js', function(done) { loadjs(['assets/file1.css', 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should support forced "css!" files', function(done) { loadjs(['css!assets/file1.css'], { success: function() { // loop through files var els = document.getElementsByTagName('link'), i = els.length, el; while (i--) { if (els[i].href.indexOf('file1.css') !== -1) done(); } } }); }); it('supports urls with query arguments', function(done) { loadjs(['assets/file1.css?x=x'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with anchor tags', function(done) { loadjs(['assets/file1.css#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { loadjs(['assets/file1.css?x=x#anchortag'], { success: function() { assert.equal(testEl.offsetWidth, 100); done(); } }); }); it('should load external css files', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], { success: function() { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '15px'); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { var styleObj = getComputedStyle(testEl); assert.equal(styleObj.getPropertyValue('padding-left'), '0px'); assert.equal(pathsNotFound.length, 1); done(); } }); }); // teardown return after(function() { // remove test div testEl.parentNode.removeChild(testEl); }); }); // ========================================================================== // Image file loading tests // ========================================================================== describe('Image file loading tests', function() { function assertLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // verify image was loaded if (img.src === src) assert.equal(img.naturalWidth > 0, true); }); } function assertNotLoaded(src) { // loop through images var imgs = document.getElementsByTagName('img'); Array.prototype.slice.call(imgs).forEach(function(img) { // fail if image was loaded if (img.src === src) assert.equal(img.naturalWidth, 0); }); } it('should load one file', function(done) { loadjs(['assets/flash.png'], { success: function() { assertLoaded('assets/flash.png'); done(); } }); }); it('should load multiple files', function(done) { loadjs(['assets/flash.png', 'assets/flash.jpg'], { success: function() { assertLoaded('assets/flash.png'); assertLoaded('assets/flash.jpg'); done(); } }); }); it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with anchor tags', function(done) { var src = 'assets/flash.png#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('supports urls with query arguments and anchor tags', function(done) { var src = 'assets/flash.png'; src += '?' + Math.random(); src += '#' + Math.random(); loadjs([src], { success: function() { assertLoaded(src); done(); } }); }); it('should support forced "img!" files', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error callback on one invalid path', function(done) { var src1 = 'assets/flash.png?' + Math.random(), src2 = 'assets/flash-doesntexist.png?' + Math.random(); loadjs(['img!' + src1, 'img!' + src2], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assertLoaded(src1); assertNotLoaded(src2); done(); } }); }); it('should support mix of img and js', function(done) { var src = 'assets/flash.png?' + Math.random(); loadjs(['img!' + src, 'assets/file1.js'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assertLoaded(src); done(); } }); }); it('should load external img files', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/mui-logo.png?'; src += Math.random(); loadjs(['img!' + src], { success: function() { assertLoaded(src); done(); } }); }); it('should call error on missing external file', function(done) { this.timeout(0); var src = 'https://www.muicss.com/static/images/'; src += 'mui-logo-doesntexist.png?' + Math.random(); loadjs(['img!' + src], { success: function() { throw new Error('Executed success callback'); }, error: function(pathsNotFound) { assertNotLoaded(src); done(); } }); }); }); // ========================================================================== // API tests // ========================================================================== describe('API tests', function() { it('should throw an error if bundle is already defined', function() { // define bundle loadjs(['assets/file1.js'], 'bundle'); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'bundle'); }; expect(fn).to.throw("LoadJS"); }); it('should create a bundle id and a callback inline', function(done) { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should chain loadjs object', function(done) { function bothDone() { if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done(); } // define bundles loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs .ready('bundle1', { success: function() { assert.equal(pathsLoaded['file1.js'], true); bothDone(); }}) .ready('bundle2', { success: function() { assert.equal(pathsLoaded['file2.js'], true); bothDone(); } }); }); it('should handle multiple dependencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file2.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }); it('should error on missing depdendencies', function(done) { loadjs('assets/file1.js', 'bundle1'); loadjs('assets/file-doesntexist.js', 'bundle2'); loadjs.ready(['bundle1', 'bundle2'], { success: function() { throw "Executed success callback"; }, error: function(depsNotFound) { assert.equal(pathsLoaded['file1.js'], true); assert.equal(depsNotFound.length, 1); assert.equal(depsNotFound[0], 'bundle2'); done(); } }); }); it('should execute callbacks on .done()', function(done) { // add handler loadjs.ready('plugin', { success: function() { done(); } }); // execute done loadjs.done('plugin'); }); it('should execute callbacks created after .done()', function(done) { // execute done loadjs.done('plugin'); // add handler loadjs.ready('plugin', { success: function() { done(); } }); }); it('should define bundles', function(done) { // define bundle loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); // use 1 second delay to let files load setTimeout(function() { loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); }, 1000); }); it('should allow bundle callbacks before definitions', function(done) { // define callback loadjs.ready('bundle', { success: function() { assert.equal(pathsLoaded['file1.js'], true); assert.equal(pathsLoaded['file2.js'], true); done(); } }); // use 1 second delay setTimeout(function() { loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle'); }, 1000); }); it('should reset dependencies statuses', function() { loadjs(['assets/file1.js'], 'cleared'); loadjs.reset(); // define bundle again var fn = function() { loadjs(['assets/file1.js'], 'cleared'); }; expect(fn).not.to.throw("LoadJS"); }); it('should indicate if bundle has already been defined', function() { loadjs(['assets/file1/js'], 'bundle1'); assert.equal(loadjs.isDefined('bundle1'), true); assert.equal(loadjs.isDefined('bundleXX'), false); }); it('should accept success callback functions to loadjs()', function(done) { loadjs('assets/file1.js', function() { done(); }); }); it('should accept success callback functions to .ready()', function(done) { loadjs.done('plugin'); loadjs.ready('plugin', function() { done(); }); }); it('should return Promise object if returnPromise is true', function() { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); // verify that response object is a Promise assert.equal(prom instanceof Promise, true); }); it('Promise object should support resolutions', function(done) { var prom = loadjs(['assets/file1.js'], {returnPromise: true}); prom.then(function() { assert.equal(pathsLoaded['file1.js'], true); done(); }); }); it('Promise object should support rejections', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom.then( function(){}, function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); } ); }); it('Promise object should support catches', function(done) { var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true}); prom .catch(function(pathsNotFound) { assert.equal(pathsNotFound.length, 1); assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js'); done(); }); }); it('supports Promises and success callbacks', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; var prom = loadjs('assets/file1.js', { success: completedFn, returnPromise: true }); prom.then(completedFn); }); it('supports Promises and bundle ready events', function(done) { var numCompleted = 0; function completedFn() { numCompleted += 1; if (numCompleted === 2) done(); }; loadjs('assets/file1.js', 'bundle1', {returnPromise: true}) .then(completedFn); loadjs.ready('bundle1', completedFn); }); }); }); <MSG> added image file extension tests, bumped version number <DFF> @@ -426,6 +426,22 @@ describe('LoadJS tests', function() { }); + it('detects png|gif|jpg|svg|webp extensions', function(done) { + let files = [ + 'assets/flash.png', + 'assets/flash.gif', + 'assets/flash.jpg', + 'assets/flash.svg', + 'assets/flash.webp' + ]; + + loadjs(files, function() { + files.forEach(file => {assertLoaded(file);}); + done(); + }); + }); + + it('supports urls with query arguments', function(done) { var src = 'assets/flash.png?' + Math.random();
16
added image file extension tests, bumped version number
0
.js
js
mit
muicss/loadjs
10064275
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064276
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064277
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064278
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064279
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064280
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064281
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064282
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064283
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064284
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064285
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064286
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064287
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064288
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064289
<NME> TextTransformation.cs <BEF> using System; using Avalonia.Media; using AvaloniaEdit.Document; namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { public TextTransformation(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } public class ForegroundTextTransformation : TextTransformation { public interface IColorMap { IBrush GetBrush(int color); } private IColorMap _colorMap; private Action<Exception> _exceptionHandler; private int _foreground; private int _background; private int _fontStyle; public ForegroundTextTransformation( IColorMap colorMap, Action<Exception> exceptionHandler, int startOffset, int endOffset, int foreground, int background, int fontStyle) : base(startOffset, endOffset) { _colorMap = colorMap; _exceptionHandler = exceptionHandler; _foreground = foreground; _background = background; _fontStyle = fontStyle; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { try { if (Length == 0) { return; } var formattedOffset = 0; var endOffset = line.EndOffset; if (StartOffset > line.Offset) { formattedOffset = StartOffset - line.Offset; } if (EndOffset < line.EndOffset) { endOffset = EndOffset; } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, _colorMap.GetBrush(_foreground), _colorMap.GetBrush(_background), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { _exceptionHandler?.Invoke(ex); } } FontStyle GetFontStyle() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) return FontStyle.Italic; return FontStyle.Normal; } FontWeight GetFontWeight() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) return FontWeight.Bold; return FontWeight.Regular; } bool IsUnderline() { if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false; } } } <MSG> Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak Attempt to fix TextTransformation leakage <DFF> @@ -1,19 +1,13 @@ using System; -using Avalonia.Media; - using AvaloniaEdit.Document; +using AM = Avalonia.Media; + namespace AvaloniaEdit.TextMate { public abstract class TextTransformation : TextSegment { - public TextTransformation(int startOffset, int endOffset) - { - StartOffset = startOffset; - EndOffset = endOffset; - } - public abstract void Transform(GenericLineTransformer transformer, DocumentLine line); } @@ -21,30 +15,14 @@ namespace AvaloniaEdit.TextMate { public interface IColorMap { - IBrush GetBrush(int color); + AM.IBrush GetBrush(int color); } - private IColorMap _colorMap; - private Action<Exception> _exceptionHandler; - private int _foreground; - private int _background; - private int _fontStyle; - - public ForegroundTextTransformation( - IColorMap colorMap, - Action<Exception> exceptionHandler, - int startOffset, - int endOffset, - int foreground, - int background, - int fontStyle) : base(startOffset, endOffset) - { - _colorMap = colorMap; - _exceptionHandler = exceptionHandler; - _foreground = foreground; - _background = background; - _fontStyle = fontStyle; - } + public IColorMap ColorMap { get; set; } + public Action<Exception> ExceptionHandler { get; set; } + public int ForegroundColor { get; set; } + public int BackgroundColor { get; set; } + public int FontStyle { get; set; } public override void Transform(GenericLineTransformer transformer, DocumentLine line) { @@ -69,40 +47,40 @@ namespace AvaloniaEdit.TextMate } transformer.SetTextStyle(line, formattedOffset, endOffset - line.Offset - formattedOffset, - _colorMap.GetBrush(_foreground), - _colorMap.GetBrush(_background), + ColorMap.GetBrush(ForegroundColor), + ColorMap.GetBrush(BackgroundColor), GetFontStyle(), GetFontWeight(), IsUnderline()); } catch(Exception ex) { - _exceptionHandler?.Invoke(ex); + ExceptionHandler?.Invoke(ex); } } - FontStyle GetFontStyle() + AM.FontStyle GetFontStyle() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) - return FontStyle.Italic; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Italic) != 0) + return AM.FontStyle.Italic; - return FontStyle.Normal; + return AM.FontStyle.Normal; } - FontWeight GetFontWeight() + AM.FontWeight GetFontWeight() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) - return FontWeight.Bold; + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Bold) != 0) + return AM.FontWeight.Bold; - return FontWeight.Regular; + return AM.FontWeight.Regular; } bool IsUnderline() { - if (_fontStyle != TextMateSharp.Themes.FontStyle.NotSet && - (_fontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) + if (FontStyle != TextMateSharp.Themes.FontStyle.NotSet && + (FontStyle & TextMateSharp.Themes.FontStyle.Underline) != 0) return true; return false;
23
Merge pull request #264 from AvaloniaUI/fixes/visualLineLeak
45
.cs
TextMate/TextTransformation
mit
AvaloniaUI/AvaloniaEdit
10064290
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064291
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064292
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064293
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064294
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064295
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064296
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064297
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064298
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064299
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064300
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064301
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064302
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064303
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064304
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } [Test] using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } } } Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Add unit tests <DFF> @@ -164,6 +164,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -183,6 +184,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -204,6 +206,7 @@ namespace AvaloniaEdit.Tests.TextMate textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); + textEditorModel.Dispose(); } [Test] @@ -220,6 +223,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -236,6 +240,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -253,6 +258,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + textEditorModel.Dispose(); } [Test] @@ -274,6 +280,78 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); + textEditorModel.Dispose(); + } + + [Test] + public void Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); + } + + [Test] + public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npuppy\npuppy"; + + document.BeginUpdate(); + + document.Insert(0, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine); + + document.BeginUpdate(); + document.Insert(7, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine); + + document.Insert(14, "*"); + Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine); + Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine); + + document.EndUpdate(); + Assert.IsNotNull(textEditorModel.InvalidRange); + document.EndUpdate(); + Assert.IsNull(textEditorModel.InvalidRange); + + Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); + textEditorModel.Dispose(); } } }
78
Add unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10064305
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: template returning 0 should be rendered Fixes #341 <DFF> @@ -895,6 +895,18 @@ $(function() { } }); + test("'0' itemTemplate should be rendered", function() { + var $element = $("#jsGrid"), + grid = new Grid($element, { + data: [{}], + fields: [ + new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) + ] + }); + + equal(grid._bodyGrid.text(), "0", "item template is rendered"); + }); + test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, {
12
Core: template returning 0 should be rendered
0
.js
tests
mit
tabalinas/jsgrid
10064306
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: template returning 0 should be rendered Fixes #341 <DFF> @@ -895,6 +895,18 @@ $(function() { } }); + test("'0' itemTemplate should be rendered", function() { + var $element = $("#jsGrid"), + grid = new Grid($element, { + data: [{}], + fields: [ + new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) + ] + }); + + equal(grid._bodyGrid.text(), "0", "item template is rendered"); + }); + test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, {
12
Core: template returning 0 should be rendered
0
.js
tests
mit
tabalinas/jsgrid
10064307
<NME> readme.hogan <BEF> ![fm logo](artwork/logo.jpg) {{pkg.description}} {{{partials.md.intro}}} ## License ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create a module var apple = new Apple(); // Render it apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or Download the [pre-built version][built] (~2k gzipped). [built]: http://wzrd.in/standalone/fruitmachine@latest ## Examples - [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/) - [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/) ## Documentation - [Introduction](docs/introduction.md) - [Getting started](docs/getting-started.md) - [Defining modules](docs/defining-modules.md) - [Slots](docs/slots.md) - [View assembly](docs/layout-assembly.md) - [Instantiation](docs/module-instantiation.md) - [Templates](docs/templates.md) - [Template markup](docs/template-markup.md) - [Rendering](docs/rendering.md) - [DOM injection](docs/injection.md) - [The module element](docs/module-el.md) - [Queries](docs/queries.md) - [Helpers](docs/module-helpers.md) - [Removing & destroying](docs/removing-and-destroying.md) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) - [API](docs/api.md) - [Events](docs/events.md) ## Tests #### With PhantomJS ``` $ npm install $ npm test ``` #### Without PhantomJS ``` $ node_modules/.bin/buster-static ``` ...then visit http://localhost:8282/ in browser ## Author {{#pkg.author}} - **{{name}}** - [@{{github}}](http://github.com/{{github}}) {{/pkg.author}} ## Contributors {{#pkg.contributors}} - **{{name}}** - [@{{github}}](http://github.com/{{github}}) {{/pkg.contributors}} ## License Copyright (c) 2014 {{pkg.organization}} Licensed under the MIT license. ## Credits and collaboration The lead developer of {{pkg.title}} is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. <MSG> Updated readme <DFF> @@ -1,7 +1,5 @@ ![fm logo](artwork/logo.jpg) -{{pkg.description}} - {{{partials.md.intro}}} ## License
0
Updated readme
2
.hogan
hogan
mit
ftlabs/fruitmachine
10064308
<NME> module-helpers.md <BEF> ## Helpers Helpers are small reusable plug-ins that you can write to add extra features to a View module ([working example](http://ftlabs.github.io/fruitmachine/examples/helpers)). ### Defining helpers A helper is simply a function accepting the View module instance as the first argument. The helper can listen to events on the View module and bolt functionality onto the view. Helpers should clear up after themselves. For example if they create variables or bind to events on `setup`, they should be unset and unbound on `teardown`. ```js var myHelper = function(module) { // Add functionality module.on('before setup', function() { /* 1 */ module.sayName = function() { return 'My name is ' + module.name; }; }); // Tidy up module.on('teardown', function() { delete module.sayName; }); }; ``` 1. *It is often useful to hook into the `before setup` event so that added functionality is available inside the module's `setup` function.* ### Attaching helpers At definition: ```js var Apple = fruitmachine.define({ name: 'apple', helpers: [ myHelper ] }); ``` ...or instantiation: ```js var apple = new Apple({ helpers: [ myHelper ] }); ``` ### Using features ```js apple.sayName(); //=> 'My name is apple' ``` ### Community Helpers ("Plugins") These helpers can be released as plugins, if you would like to submit your helper to this list, [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). - [fruitmachine-ftdomdelegate](https://github.com/ftlabs/fruitmachine-ftdomdelegate) provides [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) functionality within fruitmachine modules. - [fruitmachine-bindall](https://github.com/ftlabs/fruitmachine-bindall) automatically binds all the methods in a module to instances of that module. - [fruitmachine-media](https://github.com/ftlabs/fruitmachine-media) allows you to create responsive components. Set up media queries for different states and this plugin will allow you to hook into per state setup and teardown events when those media queries match. <MSG> Update helpers <DFF> @@ -55,6 +55,6 @@ apple.sayName(); ### Community Helpers ("Plugins") -These helpers can be released as plugins, if you would like to submit your helper to this list, [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). +Helpers can be released as plugins, if you would like to submit your helper to this list, [please raise an issue](https://github.com/ftlabs/fruitmachine/issues). - [fruitmachine-ftdomdelegate](https://github.com/ftlabs/fruitmachine-ftdomdelegate) provides [ftdomdelegate](https://github.com/ftlabs/ftdomdelegate) functionality within fruitmachine modules.
1
Update helpers
1
.md
md
mit
ftlabs/fruitmachine
10064309
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064310
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064311
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064312
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064313
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064314
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064315
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064316
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064317
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064318
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064319
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064320
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064321
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064322
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064323
<NME> AvaloniaEdit.Demo.csproj <BEF> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants> </PropertyGroup> <ItemGroup> <Compile Include="**\*.cs" Exclude="obj\**" /> </ItemGroup> <ItemGroup> <Compile Update="**\*.xaml.cs"> <DependentUpon>%(Filename)</DependentUpon> <SubType>Code</SubType> </Compile> <AvaloniaResource Include="Assets\**" /> <AvaloniaResource Include="**\*.xaml" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="Resources\SampleFiles\**\*" /> </ItemGroup> <ItemGroup> <Compile Remove="Resources\SampleFiles\source.cs" /> </ItemGroup> <ItemGroup> <PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Desktop" Version="$(AvaloniaVersion)" /> <PackageReference Include="Avalonia.Themes.Fluent" Version="$(AvaloniaVersion)"/> <ProjectReference Include="..\AvaloniaEdit\AvaloniaEdit.csproj" /> <ProjectReference Include="..\AvaloniaEdit.TextMate\AvaloniaEdit.TextMate.csproj" /> </ItemGroup> </Project> <MSG> no need for package fallback on netcore 2 preview 2 <DFF> @@ -3,7 +3,6 @@ <PropertyGroup> <OutputType>exe</OutputType> <TargetFrameworks>netcoreapp1.1;net461</TargetFrameworks> - <PackageTargetFallback>$(PackageTargetFallback);netstandard1.3;net45</PackageTargetFallback> <RuntimeIdentifiers>win7-x64;ubuntu.14.04-x64;osx.10.12-x64</RuntimeIdentifiers> <EnableDefaultCompileItems>False</EnableDefaultCompileItems> <DefineConstants>DEBUG;TRACE</DefineConstants>
0
no need for package fallback on netcore 2 preview 2
1
.csproj
Demo/AvaloniaEdit
mit
AvaloniaUI/AvaloniaEdit
10064324
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064325
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064326
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064327
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064328
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064329
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064330
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064331
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064332
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064333
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064334
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064335
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064336
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064337
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064338
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { if (_model != null) { _model.SetGrammar(grammar); } } IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId) { if (_brushes == null) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } } finally { ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations) { for (int i = 0; i < tokens.Count; i++) { var token = tokens[i]; var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null; var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0) { transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Fixed compilation <DFF> @@ -87,14 +87,14 @@ namespace AvaloniaEdit.TextMate var startIndex = token.StartIndex; var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1); - if (startIndex == endIndex || token.scopes == null || token.scopes.Length == 0) + if (startIndex == endIndex || token.Scopes == null || token.Scopes.Count == 0) { continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; - foreach (var themeRule in _theme.Match(token.scopes)) + foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) {
2
Fixed compilation
2
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10064339
<NME> jsgrid.field.select.js <BEF> (function(jsGrid, $, undefined) { var NumberField = jsGrid.NumberField; var numberValueType = "number"; var stringValueType = "string"; function SelectField(config) { this.items = []; this.selectedIndex = -1; this.valueField = ""; this.textField = ""; if(config.valueField && config.items.length) { var firstItemValue = config.items[0][config.valueField]; this.valueType = (typeof firstItemValue) === numberValueType ? numberValueType : stringValueType; } this.sorter = this.valueType; NumberField.call(this, config); } SelectField.prototype = new NumberField({ align: "center", valueType: numberValueType, itemTemplate: function(value) { var items = this.items, valueField = this.valueField, textField = this.textField, resultItem; if(valueField) { resultItem = $.grep(items, function(item, index) { return item[valueField] === value; })[0] || {}; } else { resultItem = items[value]; } var result = (textField ? resultItem[textField] : resultItem); return (result === undefined || result === null) ? "" : result; }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createSelect(); if(this.autosearch) { $result.on("change", function(e) { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createSelect(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createSelect(); (value !== undefined) && $result.val(value); return $result; }, filterValue: function() { var val = this.filterControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, insertValue: function() { var val = this.insertControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, editValue: function() { var val = this.editControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, _createSelect: function() { var $result = $("<select>"), valueField = this.valueField, textField = this.textField, selectedIndex = this.selectedIndex; $.each(this.items, function(index, item) { var value = valueField ? item[valueField] : index, text = textField ? item[textField] : item; var $option = $("<option>") .attr("value", value) .text(text) .appendTo($result); }); $result.prop("disabled", !!this.readOnly); $result.prop('selectedIndex', selectedIndex); return $result; } }); jsGrid.fields.select = jsGrid.SelectField = SelectField; }(jsGrid, jQuery)); <MSG> Single->Double Qoutes <DFF> @@ -110,8 +110,8 @@ }); $result.prop("disabled", !!this.readOnly); - $result.prop('selectedIndex', selectedIndex); - + $result.prop("selectedIndex", selectedIndex); + return $result; } });
2
Single->Double Qoutes
2
.js
field
mit
tabalinas/jsgrid
10064340
<NME> jsgrid.field.select.js <BEF> (function(jsGrid, $, undefined) { var NumberField = jsGrid.NumberField; var numberValueType = "number"; var stringValueType = "string"; function SelectField(config) { this.items = []; this.selectedIndex = -1; this.valueField = ""; this.textField = ""; if(config.valueField && config.items.length) { var firstItemValue = config.items[0][config.valueField]; this.valueType = (typeof firstItemValue) === numberValueType ? numberValueType : stringValueType; } this.sorter = this.valueType; NumberField.call(this, config); } SelectField.prototype = new NumberField({ align: "center", valueType: numberValueType, itemTemplate: function(value) { var items = this.items, valueField = this.valueField, textField = this.textField, resultItem; if(valueField) { resultItem = $.grep(items, function(item, index) { return item[valueField] === value; })[0] || {}; } else { resultItem = items[value]; } var result = (textField ? resultItem[textField] : resultItem); return (result === undefined || result === null) ? "" : result; }, filterTemplate: function() { if(!this.filtering) return ""; var grid = this._grid, $result = this.filterControl = this._createSelect(); if(this.autosearch) { $result.on("change", function(e) { grid.search(); }); } return $result; }, insertTemplate: function() { if(!this.inserting) return ""; return this.insertControl = this._createSelect(); }, editTemplate: function(value) { if(!this.editing) return this.itemTemplate.apply(this, arguments); var $result = this.editControl = this._createSelect(); (value !== undefined) && $result.val(value); return $result; }, filterValue: function() { var val = this.filterControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, insertValue: function() { var val = this.insertControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, editValue: function() { var val = this.editControl.val(); return this.valueType === numberValueType ? parseInt(val || 0, 10) : val; }, _createSelect: function() { var $result = $("<select>"), valueField = this.valueField, textField = this.textField, selectedIndex = this.selectedIndex; $.each(this.items, function(index, item) { var value = valueField ? item[valueField] : index, text = textField ? item[textField] : item; var $option = $("<option>") .attr("value", value) .text(text) .appendTo($result); }); $result.prop("disabled", !!this.readOnly); $result.prop('selectedIndex', selectedIndex); return $result; } }); jsGrid.fields.select = jsGrid.SelectField = SelectField; }(jsGrid, jQuery)); <MSG> Single->Double Qoutes <DFF> @@ -110,8 +110,8 @@ }); $result.prop("disabled", !!this.readOnly); - $result.prop('selectedIndex', selectedIndex); - + $result.prop("selectedIndex", selectedIndex); + return $result; } });
2
Single->Double Qoutes
2
.js
field
mit
tabalinas/jsgrid
10064341
<NME> es.js <BEF> (function(jsGrid) { jsGrid.locales.es = { grid: { noDataContent: "No encontrado", deleteConfirm: "Esta seguro?", pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} de {pageCount}", pagePrevText: "Anterior", pageNextText: "Siguiente", pageFirstText: "Primero", pageLastText: "Ultimo", loadMessage: "Espere, por favor...", invalidMessage: "Datos inválidos!" }, loadIndicator: { message: "Cargando..." }, fields: { control: { searchModeButtonTooltip: "Cambia a búsqueda", insertModeButtonTooltip: "Cambia a inserción", editButtonTooltip: "Editar", deleteButtonTooltip: "Suprimir", searchButtonTooltip: "Buscar", clearFilterButtonTooltip: "Borrar filtro", insertButtonTooltip: "Insertar", updateButtonTooltip: "Actualizar", cancelEditButtonTooltip: "Cancelar edición" } }, validators: { required: { message: "Campo requerido" }, rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" }, minLength: { message: "La longitud del valor esta demasiado largo" }, maxLength: { message: "La longitud del valor esta demasiado corto" }, pattern: { message: "Valor no coincide con el patrón definido" }, range: { message: "Valor fuera del intervalo definido" }, min: { message: "Valor demasiado alto" }, max: { message: "Valor demasiado bajo" } } }; }(jsGrid, jQuery)); <MSG> Update es.js <DFF> @@ -3,14 +3,14 @@ jsGrid.locales.es = { grid: { noDataContent: "No encontrado", - deleteConfirm: "Esta seguro?", + deleteConfirm: "¿Está seguro?", pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} de {pageCount}", pagePrevText: "Anterior", pageNextText: "Siguiente", pageFirstText: "Primero", pageLastText: "Ultimo", - loadMessage: "Espere, por favor...", - invalidMessage: "Datos inválidos!" + loadMessage: "Por favor, espere...", + invalidMessage: "¡Datos no válidos!" }, loadIndicator: { @@ -19,8 +19,8 @@ fields: { control: { - searchModeButtonTooltip: "Cambia a búsqueda", - insertModeButtonTooltip: "Cambia a inserción", + searchModeButtonTooltip: "Cambiar a búsqueda", + insertModeButtonTooltip: "Cambiar a inserción", editButtonTooltip: "Editar", deleteButtonTooltip: "Suprimir", searchButtonTooltip: "Buscar", @@ -33,11 +33,11 @@ validators: { required: { message: "Campo requerido" }, - rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" }, - minLength: { message: "La longitud del valor esta demasiado largo" }, - maxLength: { message: "La longitud del valor esta demasiado corto" }, - pattern: { message: "Valor no coincide con el patrón definido" }, - range: { message: "Valor fuera del intervalo definido" }, + rangeLength: { message: "La longitud del valor está fuera del intervalo definido" }, + minLength: { message: "La longitud del valor es demasiado larga" }, + maxLength: { message: "La longitud del valor es demasiado corta" }, + pattern: { message: "El valor no se ajusta al patrón definido" }, + range: { message: "Valor fuera del rango definido" }, min: { message: "Valor demasiado alto" }, max: { message: "Valor demasiado bajo" } }
10
Update es.js
10
.js
js
mit
tabalinas/jsgrid
10064342
<NME> es.js <BEF> (function(jsGrid) { jsGrid.locales.es = { grid: { noDataContent: "No encontrado", deleteConfirm: "Esta seguro?", pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} de {pageCount}", pagePrevText: "Anterior", pageNextText: "Siguiente", pageFirstText: "Primero", pageLastText: "Ultimo", loadMessage: "Espere, por favor...", invalidMessage: "Datos inválidos!" }, loadIndicator: { message: "Cargando..." }, fields: { control: { searchModeButtonTooltip: "Cambia a búsqueda", insertModeButtonTooltip: "Cambia a inserción", editButtonTooltip: "Editar", deleteButtonTooltip: "Suprimir", searchButtonTooltip: "Buscar", clearFilterButtonTooltip: "Borrar filtro", insertButtonTooltip: "Insertar", updateButtonTooltip: "Actualizar", cancelEditButtonTooltip: "Cancelar edición" } }, validators: { required: { message: "Campo requerido" }, rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" }, minLength: { message: "La longitud del valor esta demasiado largo" }, maxLength: { message: "La longitud del valor esta demasiado corto" }, pattern: { message: "Valor no coincide con el patrón definido" }, range: { message: "Valor fuera del intervalo definido" }, min: { message: "Valor demasiado alto" }, max: { message: "Valor demasiado bajo" } } }; }(jsGrid, jQuery)); <MSG> Update es.js <DFF> @@ -3,14 +3,14 @@ jsGrid.locales.es = { grid: { noDataContent: "No encontrado", - deleteConfirm: "Esta seguro?", + deleteConfirm: "¿Está seguro?", pagerFormat: "Paginas: {first} {prev} {pages} {next} {last} &nbsp;&nbsp; {pageIndex} de {pageCount}", pagePrevText: "Anterior", pageNextText: "Siguiente", pageFirstText: "Primero", pageLastText: "Ultimo", - loadMessage: "Espere, por favor...", - invalidMessage: "Datos inválidos!" + loadMessage: "Por favor, espere...", + invalidMessage: "¡Datos no válidos!" }, loadIndicator: { @@ -19,8 +19,8 @@ fields: { control: { - searchModeButtonTooltip: "Cambia a búsqueda", - insertModeButtonTooltip: "Cambia a inserción", + searchModeButtonTooltip: "Cambiar a búsqueda", + insertModeButtonTooltip: "Cambiar a inserción", editButtonTooltip: "Editar", deleteButtonTooltip: "Suprimir", searchButtonTooltip: "Buscar", @@ -33,11 +33,11 @@ validators: { required: { message: "Campo requerido" }, - rangeLength: { message: "La longitud del valor esta fuera del intervalo definido" }, - minLength: { message: "La longitud del valor esta demasiado largo" }, - maxLength: { message: "La longitud del valor esta demasiado corto" }, - pattern: { message: "Valor no coincide con el patrón definido" }, - range: { message: "Valor fuera del intervalo definido" }, + rangeLength: { message: "La longitud del valor está fuera del intervalo definido" }, + minLength: { message: "La longitud del valor es demasiado larga" }, + maxLength: { message: "La longitud del valor es demasiado corta" }, + pattern: { message: "El valor no se ajusta al patrón definido" }, + range: { message: "Valor fuera del rango definido" }, min: { message: "Valor demasiado alto" }, max: { message: "Valor demasiado bajo" } }
10
Update es.js
10
.js
js
mit
tabalinas/jsgrid
10064343
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064344
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064345
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064346
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064347
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064348
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10064349
<NME> IndentationReformatter.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace AvaloniaEdit.Indentation.CSharp { internal sealed class IndentationSettings { public string IndentString { get; set; } = "\t"; public bool LeaveEmptyLines { get; set; } = true; } internal sealed class IndentationReformatter { /// <summary> /// An indentation block. Tracks the state of the indentation. /// </summary> private struct Block { /// <summary> /// The indentation outside of the block. /// </summary> public string OuterIndent; /// <summary> /// The indentation inside the block. /// </summary> public string InnerIndent; /// <summary> /// The last word that was seen inside this block. /// Because parenthesis open a sub-block and thus don't change their parent's LastWord, /// this property can be used to identify the type of block statement (if, while, switch) /// at the position of the '{'. /// </summary> public string LastWord; /// <summary> /// The type of bracket that opened this block (, [ or { /// </summary> public char Bracket; /// <summary> /// Gets whether there's currently a line continuation going on inside this block. /// </summary> public bool Continuation; /// <summary> /// Gets whether there's currently a 'one-line-block' going on. 'one-line-blocks' occur /// with if statements that don't use '{}'. They are not represented by a Block instance on /// the stack, but are instead handled similar to line continuations. /// This property is an integer because there might be multiple nested one-line-blocks. /// As soon as there is a finished statement, OneLineBlock is reset to 0. /// </summary> public int OneLineBlock; /// <summary> /// The previous value of one-line-block before it was reset. /// Used to restore the indentation of 'else' to the correct level. /// </summary> public int PreviousOneLineBlock; public void ResetOneLineBlock() { PreviousOneLineBlock = OneLineBlock; OneLineBlock = 0; } /// <summary> /// Gets the line number where this block started. /// </summary> public int StartLine; public void Indent(IndentationSettings set) { Indent(set.IndentString); } public void Indent(string indentationString) { OuterIndent = InnerIndent; InnerIndent += indentationString; Continuation = false; ResetOneLineBlock(); LastWord = ""; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "[Block StartLine={0}, LastWord='{1}', Continuation={2}, OneLineBlock={3}, PreviousOneLineBlock={4}]", StartLine, LastWord, Continuation, OneLineBlock, PreviousOneLineBlock); } } private StringBuilder _wordBuilder; private Stack<Block> _blocks; // blocks contains all blocks outside of the current private Block _block; // block is the current block private bool _inString; private bool _inChar; private bool _verbatim; private bool _escape; private bool _lineComment; private bool _blockComment; private char _lastRealChar; // last non-comment char public void Reformat(IDocumentAccessor doc, IndentationSettings set) { Init(); while (doc.MoveNext()) { Step(doc, set); } } public void Init() { _wordBuilder = new StringBuilder(); _blocks = new Stack<Block>(); _block = new Block { InnerIndent = "", OuterIndent = "", Bracket = '{', Continuation = false, LastWord = "", OneLineBlock = 0, PreviousOneLineBlock = 0, StartLine = 0 }; _inString = false; _inChar = false; _verbatim = false; _escape = false; _lineComment = false; _blockComment = false; _lastRealChar = ' '; // last non-comment char } public void Step(IDocumentAccessor doc, IndentationSettings set) { var line = doc.Text; if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty line = line.TrimStart(); var indent = new StringBuilder(); if (line.Length == 0) { // Special treatment for empty lines: if (_blockComment || (_inString && _verbatim)) return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); if (_block.Continuation) indent.Append(set.IndentString); if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return; } if (TrimEnd(doc)) line = doc.Text.TrimStart(); var oldBlock = _block; var startInComment = _blockComment; var startInString = (_inString && _verbatim); #region Parse char by char _lineComment = false; _inChar = false; _escape = false; if (!_verbatim) _inString = false; _lastRealChar = '\n'; var c = ' '; var nextchar = line[0]; for (var i = 0; i < line.Length; i++) { if (_lineComment) break; // cancel parsing current line var lastchar = c; c = nextchar; nextchar = i + 1 < line.Length ? line[i + 1] : '\n'; if (_escape) { _escape = false; continue; } #region Check for comment/string chars switch (c) { case '/': if (_blockComment && lastchar == '*') _blockComment = false; if (!_inString && !_inChar) { if (!_blockComment && nextchar == '/') _lineComment = true; if (!_lineComment && nextchar == '*') _blockComment = true; } break; case '#': if (!(_inChar || _blockComment || _inString)) _lineComment = true; break; case '"': if (!(_inChar || _lineComment || _blockComment)) { _inString = !_inString; if (!_inString && _verbatim) { if (nextchar == '"') { _escape = true; // skip escaped quote _inString = true; } else { _verbatim = false; } } else if (_inString && lastchar == '@') { _verbatim = true; } } break; case '\'': if (!(_inString || _lineComment || _blockComment)) { _inChar = !_inChar; } break; case '\\': if ((_inString && !_verbatim) || _inChar) _escape = true; // skip next character break; } #endregion if (_lineComment || _blockComment || _inString || _inChar) { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; continue; } if (!char.IsWhiteSpace(c) && c != '[' && c != '/') { if (_block.Bracket == '{') _block.Continuation = true; } if (char.IsLetterOrDigit(c)) { _wordBuilder.Append(c); } else { if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; } #region Push/Pop the blocks switch (c) { case '{': _block.ResetOneLineBlock(); _blocks.Push(_block); _block.StartLine = doc.LineNumber; if (_block.LastWord == "switch") { _block.Indent(set.IndentString + set.IndentString); /* oldBlock refers to the previous line, not the previous block * The block we want is not available anymore because it was never pushed. * } else if (oldBlock.OneLineBlock) { // Inside a one-line-block is another statement // with a full block: indent the inner full block // by one additional level block.Indent(set, set.IndentString + set.IndentString); block.OuterIndent += set.IndentString; // Indent current line if it starts with the '{' character if (i == 0) { oldBlock.InnerIndent += set.IndentString; }*/ } else { _block.Indent(set); } _block.Bracket = '{'; break; case '}': while (_block.Bracket != '{') { if (_blocks.Count == 0) break; _block = _blocks.Pop(); } if (_blocks.Count == 0) break; _block = _blocks.Pop(); _block.Continuation = false; _block.ResetOneLineBlock(); break; case '(': case '[': _blocks.Push(_block); if (_block.StartLine == doc.LineNumber) _block.InnerIndent = _block.OuterIndent; else _block.StartLine = doc.LineNumber; _block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) + (oldBlock.Continuation ? set.IndentString : "") + (i == line.Length - 1 ? set.IndentString : new string(' ', i + 1))); _block.Bracket = c; break; case ')': if (_blocks.Count == 0) break; if (_block.Bracket == '(') { _block = _blocks.Pop(); if (IsSingleStatementKeyword(_block.LastWord)) _block.Continuation = false; } break; case ']': if (_blocks.Count == 0) break; if (_block.Bracket == '[') _block = _blocks.Pop(); break; case ';': case ',': _block.Continuation = false; _block.ResetOneLineBlock(); break; case ':': if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) { _block.Continuation = false; _block.ResetOneLineBlock(); } break; } if (!char.IsWhiteSpace(c)) { // register this char as last char _lastRealChar = c; } #endregion } #endregion if (_wordBuilder.Length > 0) _block.LastWord = _wordBuilder.ToString(); _wordBuilder.Length = 0; if (startInString) return; if (startInComment && line[0] != '*') return; if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//") return; if (line[0] == '}') { indent.Append(oldBlock.OuterIndent); oldBlock.ResetOneLineBlock(); oldBlock.Continuation = false; } else { indent.Append(oldBlock.InnerIndent); } if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') { indent.Remove(indent.Length - 1, 1); } else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') { indent.Remove(indent.Length - 1, 1); } if (line[0] == ':') { oldBlock.Continuation = true; } else if (_lastRealChar == ':' && indent.Length >= set.IndentString.Length) { if (_block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(_block.LastWord + ":", StringComparison.Ordinal)) indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length); } else if (_lastRealChar == ')') { if (IsSingleStatementKeyword(_block.LastWord)) { _block.OneLineBlock++; } } else if (_lastRealChar == 'e' && _block.LastWord == "else") { _block.OneLineBlock = Math.Max(1, _block.PreviousOneLineBlock); _block.Continuation = false; oldBlock.OneLineBlock = _block.OneLineBlock - 1; } if (doc.IsReadOnly) { // We can't change the current line, but we should accept the existing // indentation if possible (=if the current statement is not a multiline // statement). if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 && oldBlock.StartLine == _block.StartLine && _block.StartLine < doc.LineNumber && _lastRealChar != ':') { // use indent StringBuilder to get the indentation of the current line indent.Length = 0; line = doc.Text; // get untrimmed line foreach (var t in line) { if (!char.IsWhiteSpace(t)) break; indent.Append(t); } // /* */ multiline comments have an extra space - do not count it // for the block's indentation. if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') { indent.Length -= 1; } _block.InnerIndent = indent.ToString(); } return; } if (line[0] != '{') { if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{') indent.Append(set.IndentString); indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock)); } // this is only for blockcomment lines starting with *, // all others keep their old indentation if (startInComment) indent.Append(' '); if (indent.Length != (doc.Text.Length - line.Length) || !doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) || char.IsWhiteSpace(doc.Text[indent.Length])) { doc.Text = indent + line; } } private static string Repeat(string text, int count) { if (count == 0) return string.Empty; if (count == 1) return text; var b = new StringBuilder(text.Length * count); for (var i = 0; i < count; i++) b.Append(text); return b.ToString(); } private static bool IsSingleStatementKeyword(string keyword) { switch (keyword) { case "if": case "for": case "while": case "do": case "foreach": case "using": case "lock": return true; default: return false; } } private static bool TrimEnd(IDocumentAccessor doc) { var line = doc.Text; if (!char.IsWhiteSpace(line[line.Length - 1])) return false; // one space after an empty comment is allowed if (line.EndsWith("// ", StringComparison.Ordinal) || line.EndsWith("* ", StringComparison.Ordinal)) return false; doc.Text = line.TrimEnd(); return true; } } } <MSG> Fixes/csharp indentation strategy (#5) * fix from AvalonStudio csharp indentation strategy modified to actually work as expected. * install csharp indentation strategy for demo app. <DFF> @@ -179,8 +179,7 @@ namespace AvaloniaEdit.Indentation.CSharp return; indent.Append(_block.InnerIndent); indent.Append(Repeat(set.IndentString, _block.OneLineBlock)); - if (_block.Continuation) - indent.Append(set.IndentString); + if (doc.Text != indent.ToString()) doc.Text = indent.ToString(); return;
1
Fixes/csharp indentation strategy (#5)
2
.cs
cs
mit
AvaloniaUI/AvaloniaEdit