diff --git a/docs/api/config/columnshape-property.md b/docs/api/config/columnshape-property.md index f864244..ce45d68 100644 --- a/docs/api/config/columnshape-property.md +++ b/docs/api/config/columnshape-property.md @@ -19,10 +19,10 @@ columnShape?: { [field: string]: number }, autoWidth?: { - columns?: { + columns: { [field: string]: boolean }, - auto: boolean | "header" | "data", + auto?: boolean | "header" | "data", maxRows?: number, firstOnly?: boolean } @@ -34,9 +34,9 @@ columnShape?: { - `sort` - (optional) if **true** (default), the sorting is enabled in UI by clicking the column header; if **false**, the sorting is disabled - `width` - (optional) defines the width of a column; it's an object where each key is a field id and the value is the width of the column in pixels - `autoWidth` - (optional) an object that defines how column width should be calculated automatically. The default configuration uses 20 rows, and the width is calculated based on the header and data, with each field analyzed only once. The object parameters are the following: - - `columns` - (optional) an object where each key is a field id and the boolean value defines whether column width should be calculated automatically - - `auto` - (required) if set to **header**, adjusts the width to the header text; if set to **data**, adjusts the width to the cell with the widest content; if set to **true**, the width is adjusted to the content of both headers and cell. - If autowidth is set to **false**, the `width` value is set or the value of the `columnWidth` from the [`tableShape`](/api/config/tableshape-property) property is applied. + - `columns` - (required) an object where each key is a field id and the boolean value defines whether column width should be calculated automatically + - `auto` - (optional) if set to **header**, adjusts the width to the header text; if set to **data**, adjusts the width to the cell with the widest content; if set to **true**, the width is adjusted to the content of both headers and cell. + If autowidth is set to **false**, the `width` value is set or the value of the `columnWidth` from the [`tableShape`](api/config/tableshape-property.md) property is applied. - `maxRows` - (optional) the number of rows to be processed for the autoWidth calculation - `firstOnly` - (optional) if set to **true** (default), each field of the same data is analyzed only once to calculate the column width; in case of multiple columns based on the same data (e.g., the *oil* field with the *count* operation and the *oil* field with the *sum* operation), only data in the first one will be analyzed and the others will inherit this width @@ -77,6 +77,6 @@ const table = new pivot.Pivot("#root", { }); ~~~ -**Related samples:** +**Related samples**: - [Pivot 2. Auto width. Sizing columns to content](https://snippet.dhtmlx.com/tn1yw14m) - [Pivot 2. Set columns width](https://snippet.dhtmlx.com/ceu34kkn) diff --git a/docs/api/config/config-property.md b/docs/api/config/config-property.md index 8c3af3c..ce8fcce 100644 --- a/docs/api/config/config-property.md +++ b/docs/api/config/config-property.md @@ -27,14 +27,14 @@ The `config` parameters are used to define which fields will be applied as rows - `rows` - (optional) defines the rows of the Pivot table. The default value is an empty array. It can be a string which represents a single field ID or an object with the field ID and a method for data extraction; the object parameters are the following: - `field` - (required) the ID of a field - - `method` - (optional) defines a method for data aggregation in the field; methods for the time-based data fields are available by default: year, month, day, hour, minute which group data by year/month/day/hour; here you can also add the name of a custom method ([see `predicates`](/api/config/predicates-property)) for the field of any data type + - `method` - (optional) defines a method for data aggregation in the field; methods for the time-based data fields are available by default: "year", "quarter", "month", "week", "day", "hour", "minute" which group data accordingly; here you can also add the name of a custom method ([see `predicates`](api/config/predicates-property.md)) for the field of any data type - `columns` - (optional) defines columns for the Pivot table. It's an empty array by default. It can be a single field ID or an object with the field ID and a method for data extraction; the object parameters are the following: - `field` - (required) the ID of a field - `method` - (optional) defines a method for data processing (for time-based data fields). - By default, methods are available for the time-based fields (the **date** type) with the next values: "year", "quarter", "month", "week", "day", "hour", "minute". Here you can also add the name of a custom method ([see `predicates`](/api/config/predicates-property)) for the field of any data type + By default, methods are available for the time-based fields (the **date** type) with the next values: "year", "quarter", "month", "week", "day", "hour", "minute". Here you can also add the name of a custom method ([see `predicates`](api/config/predicates-property.md)) for the field of any data type - `values` - (optional) defines the data aggregation for the cells of the Pivot table. It's an empty array by default. Each element can be a string representing a data field ID and aggregation method or an object containing the field ID and the method for data aggregation. The object parameters are the following: - `field` - (required) the ID of a field - - `method` - (required) defines a method for data extraction; for methods types and their description refer to [Applying methods](/guides/working-with-data#default-methods) + - `method` - (required) defines a method for data extraction; for methods types and their description refer to [Applying methods](guides/working-with-data.md#default-methods)
@@ -49,7 +49,7 @@ You can define `values` in either of the two equally valid ways: ~~~jsx values: [ "sum(sales)", // option one - { id: "sales", method: "sum" }, // option two + { field: "sales", method: "sum" }, // option two ] ~~~ @@ -78,7 +78,7 @@ values: [ - `includes` - (optional) an array of values to be displayed from those that are already filtered; available for text and dates values :::info -When config is processed by Pivot, its properties receive extra data and if you try to return the config state via the [`api.getState()`](/api/internal/getstate-method) method, the full object will look like this: +When config is processed by Pivot, its properties receive extra data and if you try to return the config state via the [`api.getState()`](api/internal/getstate-method.md) method, the full object will look like this: ~~~jsx interface IParsedField { diff --git a/docs/api/config/configpanel-property.md b/docs/api/config/configpanel-property.md index 928f43b..c9547ad 100644 --- a/docs/api/config/configpanel-property.md +++ b/docs/api/config/configpanel-property.md @@ -50,9 +50,9 @@ const table = new pivot.Pivot("#root", { }); ~~~ -**Related sample:** [Pivot 2.0: Toggle visibility of configuration panel](https://snippet.dhtmlx.com/1xq1x5bo) +**Related sample**: [Pivot 2.0: Toggle visibility of configuration panel](https://snippet.dhtmlx.com/1xq1x5bo) -**Related articles:** -- [`show-config-panel` event](/api/events/show-config-panel-event) -- [`showConfigPanel()` method](/api/methods/showconfigpanel-method) -- [Controlling visibility of Configuration panel](/guides/configuration#controlling-visibility-of-configuration-panel) +**Related articles**: +- [`show-config-panel` event](api/events/show-config-panel-event.md) +- [`showConfigPanel()` method](api/methods/showconfigpanel-method.md) +- [Controlling visibility of Configuration panel](guides/configuration.md#controlling-visibility-of-configuration-panel) diff --git a/docs/api/config/fields-property.md b/docs/api/config/fields-property.md index 6dd054b..996d257 100644 --- a/docs/api/config/fields-property.md +++ b/docs/api/config/fields-property.md @@ -32,21 +32,21 @@ Each object in the `fields` array should have the following properties: - `id` - (required) the ID of a field - `label` - (optional) the field label to be displayed in GUI -- `type` - (required) data type in a field ( "number", "date", or "string") +- `type` - (required) data type in a field ( "number", "date", or "text") - `sort` - (optional) defines the default sorting order for the field. Accepts "asc", "desc", or a custom sorting function -- `format` - (optional) allows customizing the format of numbers and dates in a field; the format will be also applied during [export](/guides/exporting-data) +- `format` - (optional) allows customizing the format of numbers and dates in a field; the format will be also applied during [export](guides/exporting-data.md) - `string` - (optional) the format for dates (by default, Pivot uses `dateFormat` from locale) - `boolean` - (optional) if set to **false**, a number is displayed as is, without any formatting - `numberFormatOptions` - (optional) an object with options for formatting numeric fields; by default, numbers will be shown with a maximum of 3 decimal digits and group separation for the integer part is applied. - `minimumIntegerDigits`(number) - (optional) the minimum number of integer (for example, if the value is set to 2, the number 1 will be shown as "01"); the default is 1; - - `minimumFractionDigits`(number) - (optional) the minimum number of fraction digits to use (for example, if the value is set to 2, the number 10.5 will be shown as "10.50"); the default is 1; + - `minimumFractionDigits`(number) - (optional) the minimum number of fraction digits to use (for example, if the value is set to 2, the number 10.5 will be shown as "10.50"); the default is 0; - `maximumFractionDigits`(number) - (optional) the maximum number of fraction digits to use (for example, if the value is set to 2, the number 10.3333... will be shown as "10.33"); the default is 3; For more details about digit options refer to [Digit options](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumintegerdigits) - `prefix` (string) - (optional) a string (before a number) for additional symbols like currency - `suffix` (string) - (optional) a string (after a number) for additional symbols like currency :::info -If a template is applied via the [`tableShape`](/api/config/tableshape-property) property, it will override the `format` settings. +If a template is applied via the [`tableShape`](api/config/tableshape-property.md) property, it will override the `format` settings. ::: ### Example @@ -106,7 +106,7 @@ const table = new pivot.Pivot("#root", { **Related articles**: -- [Number formatting](/guides/localization/#number-formatting) -- [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields) +- [Number formatting](guides/localization.md#number-formatting) +- [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields) -**Related sample:** [Pivot 2. Defining fields formats](https://snippet.dhtmlx.com/77nc4j8v) \ No newline at end of file +**Related sample**: [Pivot 2. Defining fields formats](https://snippet.dhtmlx.com/77nc4j8v) \ No newline at end of file diff --git a/docs/api/config/headershape-property.md b/docs/api/config/headershape-property.md index 97fa1a8..5608770 100644 --- a/docs/api/config/headershape-property.md +++ b/docs/api/config/headershape-property.md @@ -76,8 +76,8 @@ new pivot.Pivot("#pivot", { **Related samples**: - [Pivot 2. Vertical orientation of text in grid headers](https://snippet.dhtmlx.com/4qroi8ka) - [Pivot 2. Collapsible columns](https://snippet.dhtmlx.com/pt2ljmcm) -- [Pivot 2. Adding сustom CSS for table and header cells](https://snippet.dhtmlx.com/nfdcs4i2) +- [Pivot 2. Adding custom CSS for table and header cells](https://snippet.dhtmlx.com/nfdcs4i2) **Related articles**: -- [Configuration](/guides/configuration) -- [Cell style](/guides/stylization/#cell-style) +- [Configuration](guides/configuration.md) +- [Cell style](guides/stylization.md#cell-style) diff --git a/docs/api/config/limits-property.md b/docs/api/config/limits-property.md index 6bb997f..819b2d3 100644 --- a/docs/api/config/limits-property.md +++ b/docs/api/config/limits-property.md @@ -10,7 +10,7 @@ description: You can learn about the limits config in the documentation of the D @short: Optional. Defines the maximum limit for the number of rows and columns in the final dataset -Please, also refer to [Limiting data](/guides/working-with-data#limiting-loaded-data). +Please, also refer to [Limiting data](guides/working-with-data.md#limiting-loaded-data). ### Usage @@ -58,4 +58,4 @@ const table = new pivot.Pivot("#root", { }); ~~~ -**Related sample:** [Pivot 2. Data limits](https://snippet.dhtmlx.com/7ryns8oe) +**Related sample**: [Pivot 2. Data limits](https://snippet.dhtmlx.com/7ryns8oe) diff --git a/docs/api/config/locale-property.md b/docs/api/config/locale-property.md index af2375b..96b0b6d 100644 --- a/docs/api/config/locale-property.md +++ b/docs/api/config/locale-property.md @@ -18,10 +18,10 @@ locale?: object; ### Default config -By default, Pivot uses the [English](/guides/localization/#default-locale) locale. You can set it to the custom locale as well. +By default, Pivot uses the [English](guides/localization.md#default-locale) locale. You can set it to the custom locale as well. :::tip -To change the current locale dynamically, you can use the [`setLocale()`](/api/methods/setlocale-method) method of Pivot +To change the current locale dynamically, you can use the [`setLocale()`](api/methods/setlocale-method.md) method of Pivot ::: ### Example diff --git a/docs/api/config/methods-property.md b/docs/api/config/methods-property.md index f8b6c93..4541b0c 100644 --- a/docs/api/config/methods-property.md +++ b/docs/api/config/methods-property.md @@ -68,7 +68,7 @@ defaultMethods = { }; ~~~ -The definition of each method you can see here: [Applying methods](/guides/working-with-data#default-methods) +The definition of each method you can see here: [Applying methods](guides/working-with-data.md#default-methods) ## Example @@ -158,6 +158,6 @@ const table = new pivot.Pivot("#root", { }); ~~~ -**Related sample:** [Pivot 2. Custom maths methods](https://snippet.dhtmlx.com/lv90d8q2) +**Related sample**: [Pivot 2. Custom maths methods](https://snippet.dhtmlx.com/lv90d8q2) -**Related article**: [Applying maths methods](/guides/working-with-data#applying-maths-methods) +**Related article**: [Applying maths methods](guides/working-with-data.md#applying-maths-methods) diff --git a/docs/api/config/predicates-property.md b/docs/api/config/predicates-property.md index e014e43..f7a4406 100644 --- a/docs/api/config/predicates-property.md +++ b/docs/api/config/predicates-property.md @@ -41,12 +41,14 @@ The property is an object where a key is the name of a custom function and value - `type` - (optional) defines which field type will be applied: "number"|"text"|"date"|"tuple". "tuple" is a combo filter applied for numeric values (data will be filtered by the numeric value but in filter the text value will be displayed) - `format` - (optional) the function that defines the format for displaying filter options; if no format is defined, the one from the template parameter will be applied; if the type here (for the `filter` object) is not specified, the format will be applied for the type set for the `type` parameter of the predicate - `handler` - (required for custom predicates) the function that defines how data should be processed; the function should take a single argument as the value to be processed and return the processed value -- `template` - (optional) the function that defines how data should be displayed; the function returns the processed value and it takes the value returned by `handler` and if necessary you can localize text values using [`locale`](/api/config/locale-property). +- `template` - (optional) the function that defines how data should be displayed; the function returns the processed value and it takes the value returned by `handler` and if necessary you can localize text values using [`locale`](api/config/locale-property.md). The following default predicates are applied in case no predicate is specified via the `predicates` property: ~~~jsx const defaultPredicates = { + // a service predicate that represents the raw (unprocessed) value + $empty: { label: (type) => `Raw ${type}`, type: ["number", "date", "text"] }, year: { label: "Year", type: "date", filter: { type: "number" } }, quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, month: { label: "Month", type: "date", filter: { type: "tuple" } }, @@ -110,6 +112,6 @@ const table = new pivot.Pivot("#pivot", { }); ~~~ -**Related article**: [Processing data with predicates](/guides/working-with-data#processing-data-with-predicates) +**Related article**: [Processing data with predicates](guides/working-with-data.md#processing-data-with-predicates) **Related sample**: [Pivot 2. Custom predicates](https://snippet.dhtmlx.com/mhymus00) diff --git a/docs/api/config/readonly-property.md b/docs/api/config/readonly-property.md index f29b4ad..ac807ad 100644 --- a/docs/api/config/readonly-property.md +++ b/docs/api/config/readonly-property.md @@ -49,4 +49,4 @@ const table = new pivot.Pivot("#root", { }); ~~~ -**Related sample:** [Pivot 2. Readonly mode](https://snippet.dhtmlx.com/0k0mvycv) \ No newline at end of file +**Related sample**: [Pivot 2. Readonly mode](https://snippet.dhtmlx.com/0k0mvycv) \ No newline at end of file diff --git a/docs/api/config/tableshape-property.md b/docs/api/config/tableshape-property.md index d07bc93..afa57d1 100644 --- a/docs/api/config/tableshape-property.md +++ b/docs/api/config/tableshape-property.md @@ -54,7 +54,7 @@ tableShape?: { - `templates` - (optional) allows setting templates to a cell; it's an object where: - each key is a field id - the value is a function that returns a string and receives cell value and operation. All columns based on the specified field will have the related template applied. For example, it allows setting the units of measurement or returning the required number of digits after the decimal point for numeric values, etc. See the example below. -- `marks` - (optional) allows marking a cell with the required values. It's an object where keys are CSS class names and values are either a function or one of the predefined strings ("max", "min"). The function should return boolean for the checked value. If **true** is returned, the css class is assigned to the cell. More information with examples see here [Marking cells](/guides/stylization#cell-style). +- `marks` - (optional) allows marking a cell with the required values. It's an object where keys are CSS class names and values are either a function or one of the predefined strings ("max", "min"). The function should return boolean for the checked value. If **true** is returned, the css class is assigned to the cell. More information with examples see here [Marking cells](guides/stylization.md#cell-style). - `sizes` - (optional) defines the following size parameters of the table: - `rowHeight` - (optional) the row height in the Pivot table in pixels. The default value is 34 - `headerHeight` - (optional) the header height in pixels; the default value is 30 @@ -67,12 +67,12 @@ tableShape?: { - `method` - (optional) a string that can represent the operation performed on a cell (e.g., "sum", "count", etc.) - `isTotal` - (optional) defines whether a cell belongs to a total row, total column, or both: "row"|"column"|"both The `cellStyle` function returns a string, which can be used as a CSS class name to apply specific styles to a cell. -- `tree` - (optional) if set to **true**, enables the tree mode when data can be presented with expandable rows, the default value is **false**. More information with examples see here [Switching to the tree mode](/guides/configuration/#enabling-the-tree-mode) +- `tree` - (optional) if set to **true**, enables the tree mode when data can be presented with expandable rows, the default value is **false**. More information with examples see here [Switching to the tree mode](guides/configuration.md#enabling-the-tree-mode) - `totalColumn` - (optional) if **true**, enables generating the total column with total values for rows (**false** is set by default). If the value is set to "sumOnly", the column with the total sum value will be generated (available only for sum operations) - `totalRow` - (optional) if **true**, enables generating the footer with total values (**false** is set by default). If the value is set to "sumOnly", the row with the total row value will be generated (available only for sum operations) - `cleanRows` - (optional) if set to **true**, the duplicate values in scale columns are hidden in the table view. The default value is **false** -- `split` - (optional) allows freezing columns on the right or left depending on the parameter specified (refer to [Freezing columns](/guides/configuration/#freezing-columns)): - - `left` (boolean) - if set to **true** (**false** is set by default), fixes the columns from the left, which makes columns static and visible while scrolling. The number of columns that are split is equal to the number of the rows fields that are defined in the [`config`](/api/config/config-property) property +- `split` - (optional) allows freezing columns on the right or left depending on the parameter specified (refer to [Freezing columns](guides/configuration.md#freezing-columns)): + - `left` (boolean) - if set to **true** (**false** is set by default), fixes the columns from the left, which makes columns static and visible while scrolling. The number of columns that are split is equal to the number of the rows fields that are defined in the [`config`](api/config/config-property.md) property - `right` (boolean) - fixes total columns on the right; default value is **false** By default, `tableShape` is undefined, implying that no total row, no total column is present, no templates and marks are applied, the data is shown as a table and not a tree, and columns are not fixed during scroll. @@ -118,14 +118,14 @@ const table = new pivot.Pivot("#root", { }); ~~~ -**Related samples:** +**Related samples**: - [Pivot 2. Tree mode](https://snippet.dhtmlx.com/6ylkoukn) - [Pivot 2. Frozen (fixed) columns](https://snippet.dhtmlx.com/lahf729o) - [Pivot 2. Set row, header, footer height and all columns width](https://snippet.dhtmlx.com/x46uyfy9) - [Pivot 2. Clean rows](https://snippet.dhtmlx.com/rwwhgv2w?tag=pivot) -- [Pivot 2. Adding сustom CSS for table and header cells](https://snippet.dhtmlx.com/nfdcs4i2) +- [Pivot 2. Adding custom CSS for table and header cells](https://snippet.dhtmlx.com/nfdcs4i2) **Related articles**: -- [Configuration](/guides/configuration) -- [Cell style](/guides/stylization/#cell-style) +- [Configuration](guides/configuration.md) +- [Cell style](guides/stylization.md#cell-style) diff --git a/docs/api/events/add-field-event.md b/docs/api/events/add-field-event.md index cd026da..ce9b1e5 100644 --- a/docs/api/events/add-field-event.md +++ b/docs/api/events/add-field-event.md @@ -29,17 +29,17 @@ The callback of the action takes an object with the following parameters: - `area` - (required) the name of the area where a new field is added, which can be "rows", "columns" or "values" area - `field` - (required) the name of a field - `method` - (optional) defines a method for data aggregation (if not specified, the first method suitable for this data type is set); a method can be one of the following: - - it's required for the **values** area, it's a string with one of the data operation types: [Default methods](/guides/working-with-data#default-methods) + - it's required for the **values** area, it's a string with one of the data operation types: [Default methods](guides/working-with-data.md#default-methods) - it's optional for the **rows** and **columns** areas and if the value is set it's a predicate; it can be a custom predicate or one from default values: "year", "quarter", "month", "week", "day", "hour", "minute". By default, a raw value is set. - If a custom predicate or method is set, the id should be specified for the [predicates](/api/config/predicates-property) or [methods](/api/config/methods-property) property. + If a custom predicate or method is set, the id should be specified for the [predicates](api/config/predicates-property.md) or [methods](api/config/methods-property.md) property. :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Example -In the example below we use the [`api.intercept()`](/api/internal/intercept-method) method to add a new method to the value field with the **number** data type: +In the example below we use the [`api.intercept()`](api/internal/intercept-method.md) method to add a new method to the value field with the **number** data type: ~~~jsx {20-27} const table = new pivot.Pivot("#root", { @@ -71,4 +71,4 @@ table.api.intercept("add-field", (ev) => { }); ~~~ -**Related articles**: [api.intercept()](/api/internal/intercept-method) +**Related articles**: [api.intercept()](api/internal/intercept-method.md) diff --git a/docs/api/events/apply-filter-event.md b/docs/api/events/apply-filter-event.md index 517788f..96d17c5 100644 --- a/docs/api/events/apply-filter-event.md +++ b/docs/api/events/apply-filter-event.md @@ -26,13 +26,13 @@ The callback of the action takes an object with the following parameters: - `field` - (required) the field id to which filter will be applied - `filter` - (required) filter type: - for text values: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith - - for numeric values: greater: less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains + - for numeric values: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains - for date types: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween - - `value` - (required) the value to filter by - - `includes` - (required) an array of values to be displayed from those that are already filtered; available for text and date values + - `value` - (optional) the value to filter by + - `includes` - (optional) an array of values to be displayed from those that are already filtered; available for text and date values :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Example @@ -62,4 +62,4 @@ table.api.on("apply-filter", (ev) => { }); ~~~ -**Related articles**: [api.on()](/api/internal/on-method) +**Related articles**: [api.on()](api/internal/on-method.md) diff --git a/docs/api/events/delete-field-event.md b/docs/api/events/delete-field-event.md index 0f32c84..12cb966 100644 --- a/docs/api/events/delete-field-event.md +++ b/docs/api/events/delete-field-event.md @@ -27,12 +27,12 @@ The callback of the action takes an object with the following parameters: - `id` - (required) the id of a field that is removed :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Example -In the example below, the `delete-field` action is triggered via the [`api.exec()`](/api/internal/exec-method) method. The last field is removed from the **values** area. The [`api.getState()`](/api/internal/getstate-method) method here is used to get the current state of the Pivot [`config`](/api/config/config-property). The action will be triggered with the button click. +In the example below, the `delete-field` action is triggered via the [`api.exec()`](api/internal/exec-method.md) method. The last field is removed from the **values** area. The [`api.getState()`](api/internal/getstate-method.md) method here is used to get the current state of the Pivot [`config`](api/config/config-property.md). The action will be triggered with the button click. ~~~jsx {31-34} const table = new pivot.Pivot("#root", { diff --git a/docs/api/events/move-field-event.md b/docs/api/events/move-field-event.md index 8162524..c4aef5c 100644 --- a/docs/api/events/move-field-event.md +++ b/docs/api/events/move-field-event.md @@ -16,8 +16,8 @@ description: You can learn about the move-field event in the documentation of th "move-field": ({ area: string, id: string | number, - before?: id, - after?: id + before?: string, + after?: string }) => void | boolean; ~~~ @@ -31,7 +31,7 @@ The callback of the action takes an object with the following parameters: - `after` - (optional) the id of a field after which the moved field is placed :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Example @@ -62,4 +62,4 @@ table.api.on("move-field", (ev) => { }); ~~~ -**Related articles**: [api.on()](/api/internal/on-method) +**Related articles**: [api.on()](api/internal/on-method.md) diff --git a/docs/api/events/open-filter-event.md b/docs/api/events/open-filter-event.md index 8b4796c..256cf26 100644 --- a/docs/api/events/open-filter-event.md +++ b/docs/api/events/open-filter-event.md @@ -27,7 +27,7 @@ The callback of the action takes the next parameters: - `id` - the id of a field; if there's a single id argument with null value, the filter will be closed. :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Returns diff --git a/docs/api/events/render-table-event.md b/docs/api/events/render-table-event.md index 9137b67..2233ea2 100644 --- a/docs/api/events/render-table-event.md +++ b/docs/api/events/render-table-event.md @@ -42,13 +42,13 @@ The callback of the action takes the `config` object with the following paramete - `columns` - (optional) columns array with the next parameters for each object: - `id` (number) - (required) the id of a column - - `cell` (any) - (optional) a template with the cell content (please, refer to [Adding templates via the template helper](/guides/configuration/#adding-a-template-via-the-template-helper)) - - `template` - (optional) the template that is defined via the [`tableShape`](/api/config/tableshape-property) property + - `cell` (any) - (optional) a template with the cell content (please, refer to [Adding templates via the template helper](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (optional) the template that is defined via the [`tableShape`](api/config/tableshape-property.md) property - `fields` (array) - (optional) defines fields in the hierarchical column in the tree mode. Reflects fields displayed in this column on different levels - `field` - (optional) it's a string which is the id of a field - `method` (string) - (optional) a method, if defined for a field in this column - `methods` (array) - (optional) defines methods applied to fields in the hierarchical column in the tree mode - - `format` (string or object) - (required) date format or number format (refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields)) + - `format` (string or object) - (required) date format or number format (refer to [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields)) - `isNumeric` (boolean) - (optional) defines whether a column contains numeric values - `isTotal` (boolean) - (optional) defines whether it is a total column - `area` (string) - (optional) an area where the column is rendered: "rows", "columns", "values" @@ -59,7 +59,7 @@ The callback of the action takes the `config` object with the following paramete - `value` (any) - (required) raw value, if a cell belongs to "columns" area - `field` (string) - (required) a field, which value is displayed, if a cell belongs to "columns" area - `method` (string) - (required) the field predicate, if a cell belongs to "columns" area and predicate is defined - - `format` (string or object) - date format or number format (refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields)) + - `format` (string or object) - date format or number format (refer to [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields)) - `footer` - (optional) a header label or an object with footer settings which are the same as the header settings - `data` - (optional) an array of objects with data for the table; each object represents a row: - `id` (number) - (required) row id @@ -72,10 +72,10 @@ The callback of the action takes the `config` object with the following paramete - `left` (number) - the number of fixed columns from the left - `right` (number) - the number of fixed columns from the right - `tree` - (optional) defines if the tree mode is enabled (**true** if enabled) -- `cellStyle` - (optional) an object where each key is the field id and the value is a function that returns a string. All columns based on the specified field will have the related template applied. +- `cellStyle` - (optional) a function that applies a custom style to a cell. It receives the row and column objects and returns a string with a CSS class name: `(row, col) => string` :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Returns @@ -85,7 +85,7 @@ If the event handler returns **false**, it will block the operation in question. ### Example -The next example shows how to output the [`config`](/api/config/config-property) object to console and add a footer. +The next example shows how to output the [`config`](api/config/config-property.md) object to console and add a footer. ~~~jsx {20-28} const table = new pivot.Pivot("#root", { @@ -118,7 +118,7 @@ table.api.intercept("render-table", (ev) => { }); ~~~ -The next example shows how to make all rows expand/collapse with the button click. The tree mode should be enabled via the [`tableShape`](/api/config/tableshape-property) property. +The next example shows how to make all rows expand/collapse with the button click. The tree mode should be enabled via the [`tableShape`](api/config/tableshape-property.md) property. ~~~jsx const table = new pivot.Pivot("#root", { @@ -152,7 +152,7 @@ const table = new pivot.Pivot("#root", { }); const api = table.api; -const table = api.getTable(); +const tableApi = api.getTable(); // setting all table branches closed on the table config update api.intercept("render-table", (ev) => { @@ -163,16 +163,16 @@ api.intercept("render-table", (ev) => { }); function openAll() { - table.exec("open-row", { id: 0, nested: true }); + tableApi.exec("open-row", { id: 0, nested: true }); } function closeAll() { - table.exec("close-row", { id: 0, nested: true }); + tableApi.exec("close-row", { id: 0, nested: true }); } ~~~ -See also how to configure the split feature using the `render-table` event: [Freezing columns](/guides/configuration#freezing-columns). +See also how to configure the split feature using the `render-table` event: [Freezing columns](guides/configuration.md#freezing-columns). -**Related article:** [pivot.template helper](/api/helpers/template) +**Related article**: [pivot.template helper](api/helpers/template.md) -**Related sample:** [Pivot 2. Custom frozen (fixed) columns (your number)](https://snippet.dhtmlx.com/53erlmgp) +**Related sample**: [Pivot 2. Custom frozen (fixed) columns (your number)](https://snippet.dhtmlx.com/53erlmgp) diff --git a/docs/api/events/show-config-panel-event.md b/docs/api/events/show-config-panel-event.md index aab0430..d4ab871 100644 --- a/docs/api/events/show-config-panel-event.md +++ b/docs/api/events/show-config-panel-event.md @@ -25,7 +25,7 @@ The callback of the action takes an object with the following parameter: - `mode` - (required) if the value is set to **true** (default), the Configuration panel is shown, and it's set to **false** when the Configuration panel is hidden :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Example @@ -56,5 +56,5 @@ table.api.exec("show-config-panel", { ~~~ **Related articles**: -- [`showConfigPanel()` method](/api/methods/showconfigpanel-method) -- [`configPanel` property](/api/config/configpanel-property) +- [`showConfigPanel()` method](api/methods/showconfigpanel-method.md) +- [`configPanel` property](api/config/configpanel-property.md) diff --git a/docs/api/events/update-config-event.md b/docs/api/events/update-config-event.md index 7e2b46c..9ccce91 100644 --- a/docs/api/events/update-config-event.md +++ b/docs/api/events/update-config-event.md @@ -25,7 +25,7 @@ The action is useful for saving a user's aggregation configuration so that it ca ### Parameters -The callback of the action takes an object with the processed [`config`](/api/config/config-property) parameters: +The callback of the action takes an object with the processed [`config`](api/config/config-property.md) parameters: - `rows` - rows of the Pivot table. An object with the field ID and a method for data extraction; the object parameters are the following: - `field` - the ID of a field @@ -36,11 +36,11 @@ The callback of the action takes an object with the processed [`config`](/api/co By default, methods are available for the time-based fields (the **date** type) with the next values: "year", "quarter", "month", "week", "day", "hour", "minute" - `values` - defines the data aggregation for the cells of the Pivot table. It's an object containing the field ID and the method for data aggregation. The object parameters are the following: - `field` - the ID of a field - - `method` - defines a method for data extraction; about methods and possible options refer to [Applying methods](/guides/working-with-data#default-methods) -- `filters` - (optional) defines how data is filtered in the table; it's an object with field IDs and data aggregation method. The description of the `filter` object you can see here: [`config`](/api/config/config-property) + - `method` - defines a method for data extraction; about methods and possible options refer to [Applying methods](guides/working-with-data.md#default-methods) +- `filters` - (optional) defines how data is filtered in the table; it's an object with field IDs and data aggregation method. The description of the `filter` object you can see here: [`config`](api/config/config-property.md) :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Returns @@ -59,11 +59,11 @@ const table = new pivot.Pivot("#root", { columns: [], values: [ { - id: "title", + field: "title", method: "count" }, { - id: "score", + field: "score", method: "max" } ] @@ -75,4 +75,4 @@ table.api.on("update-config", (config) => { }); ~~~ -**Related articles**: [api.intercept()](/api/internal/intercept-method) +**Related articles**: [api.intercept()](api/internal/intercept-method.md) diff --git a/docs/api/events/update-value-event.md b/docs/api/events/update-field-event.md similarity index 84% rename from docs/api/events/update-value-event.md rename to docs/api/events/update-field-event.md index e14c7fe..320e93e 100644 --- a/docs/api/events/update-value-event.md +++ b/docs/api/events/update-field-event.md @@ -26,13 +26,13 @@ The callback of the action takes an object with the following parameters: - `id` - (required) the id of a field that is updated - `method` - (required) the method can be one of the following: - - for the **values** area, it's a string with one of the data operation types: [Default methods](/guides/working-with-data#default-methods) + - for the **values** area, it's a string with one of the data operation types: [Default methods](guides/working-with-data.md#default-methods) - for the **rows** and **columns** areas it can be data predicate value with one of the next values: "year", "quarter", "month", "week", "day", "hour", "minute". By default, a raw value is set. - If a custom predicate or method is set, the id should be specified for the [predicate](/api/config/predicates-property) or [methods](/api/config/methods-property) property. + If a custom predicate or method is set, the id should be specified for the [predicate](api/config/predicates-property.md) or [methods](api/config/methods-property.md) property. - `area` - (required) the name of the area where a field is updated, which can be "rows", "columns" or "values" area :::info -For handling the inner events you can use the [Event Bus methods](/api/overview/internal-eventbus-overview) +For handling the inner events you can use the [Event Bus methods](api/overview/internal-eventbus-overview.md) ::: ### Example @@ -63,5 +63,5 @@ table.api.on("update-field", (ev) => { ~~~ **Related articles**: -- [api.on()](/api/internal/on-method) -- [methods](/api/config/methods-property) +- [api.on()](api/internal/on-method.md) +- [methods](api/config/methods-property.md) diff --git a/docs/api/helpers/template.md b/docs/api/helpers/template.md index dedf461..be2dc08 100644 --- a/docs/api/helpers/template.md +++ b/docs/api/helpers/template.md @@ -35,13 +35,13 @@ For body cells the function takes the next parameters: - `$level` (boolean)- (optional) branch index - `column` - (required) an object with column data: - `id` (number) - (required) the id of a column - - `cell` (any) - (optional) a template with the cell content (please, refer to [Adding templates via the template helper](/guides/configuration/#adding-a-template-via-the-template-helper)) - - `template` - (optional) the template that is defined via the [`tableShape`](/api/config/tableshape-property) property + - `cell` (any) - (optional) a template with the cell content (please, refer to [Adding templates via the template helper](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (optional) the template that is defined via the [`tableShape`](api/config/tableshape-property.md) property - `fields` (array) - (optional) defines fields in the hierarchical column in the tree mode. Reflects fields displayed in this column on different levels - `field` - (optional) it's a string which is the id of a field - `method` (string) - (optional) a method, if defined for a field in this column - `methods` (array) - (optional) defines methods applied to fields in the hierarchical column in the tree mode - - `format` (string or object) - (required) date format or number format (please refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields)) + - `format` (string or object) - (required) date format or number format (please refer to [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields)) - `isNumeric` (boolean) - (optional) defines whether a column contains numeric values - `isTotal` (boolean) - (optional) defines whether it is a total column - `area` (string) - (optional) an area where the column is rendered: "rows", "columns", "values" @@ -52,7 +52,7 @@ For body cells the function takes the next parameters: - `value` (any) - (required) raw value, if a cell belongs to "columns" area - `field` (string) - (required) a field, which value is displayed, if a cell belongs to "columns" area - `method` (string) - (required) the field predicate, if a cell belongs to "columns" area and predicate is defined - - `format` (string or object) - date format or number format (please refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields)) + - `format` (string or object) - date format or number format (please refer to [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields)) For header cells the function parameters are the following: @@ -66,12 +66,12 @@ For header cells the function parameters are the following: - `value` (any) - (required) raw value, if a cell belongs to "columns" area - `field` (string) - (required) a field, which value is displayed, if a cell belongs to "columns" area - `method` (string) - (required) a field predicate, if a cell belongs to "columns" area and predicate is defined - - `format` (string or object) - (required) date format or number format (please refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields)) + - `format` (string or object) - (required) date format or number format (please refer to [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields)) - `column` - (required) an object with column data (the same as for the body cell) ### Example -The snippet below shows how to define templates via the `pivot.template` helper. The helper is applied right before the table renders, which is done by intercepting the [render-table](/api/events/render-table-event) event using the [api.intercept()](/api/internal/intercept-method) method. +The snippet below shows how to define templates via the `pivot.template` helper. The helper is applied right before the table renders, which is done by intercepting the [render-table](api/events/render-table-event.md) event using the [api.intercept()](api/internal/intercept-method.md) method. The snippet demonstrates how you can add icons to: @@ -82,8 +82,8 @@ The snippet demonstrates how you can add icons to: -**Related articles:** +**Related articles**: -- [`render-table`](/api/events/render-table-event) -- [Applying templates to cells](/guides/configuration/#applying-templates-to-cells) -- [Applying templates to headers](/guides/configuration/#applying-templates-to-headers) \ No newline at end of file +- [`render-table`](api/events/render-table-event.md) +- [Applying templates to cells](guides/configuration.md#applying-templates-to-cells) +- [Applying templates to headers](guides/configuration.md#applying-templates-to-headers) \ No newline at end of file diff --git a/docs/api/internal/detach-method.md b/docs/api/internal/detach-method.md index 8284136..7861b36 100644 --- a/docs/api/internal/detach-method.md +++ b/docs/api/internal/detach-method.md @@ -22,7 +22,7 @@ api.detach(tag: number | string ): void; ### Example -In the example below we add an object with the **tag** property to the [`api.on()`](/api/internal/on-method) handler, and then we use the `api.detach()` method to stop logging the [`open-filter`](/api/events/open-filter-event) action. +In the example below we add an object with the **tag** property to the [`api.on()`](api/internal/on-method.md) handler, and then we use the `api.detach()` method to stop logging the [`open-filter`](api/events/open-filter-event.md) action. ~~~jsx {31-34} // create Pivot diff --git a/docs/api/internal/exec-method.md b/docs/api/internal/exec-method.md index 54f234f..c800f77 100644 --- a/docs/api/internal/exec-method.md +++ b/docs/api/internal/exec-method.md @@ -16,7 +16,7 @@ description: You can learn about the exec method in the documentation of the DHT api.exec( event: string, config: object -): void; +): Promise; ~~~ ## Parameters @@ -27,12 +27,12 @@ api.exec( ## Actions :::info -The full list of Pivot events can be found [**here**](/api/overview/events-overview) +The full list of Pivot events can be found [**here**](api/overview/events-overview.md) ::: ## Example -In the example below, the [`delete-field`](/api/events/delete-field-event) event is triggered via the `api.exec()`method. The last field is removed from the **values** area. The [`api.getState()`](/api/internal/getstate-method) method here is used to get the current state of the Pivot [`config`](/api/config/config-property). The event will be triggered with the button click. +In the example below, the [`delete-field`](api/events/delete-field-event.md) event is triggered via the `api.exec()`method. The last field is removed from the **values** area. The [`api.getState()`](api/internal/getstate-method.md) method here is used to get the current state of the Pivot [`config`](api/config/config-property.md). The event will be triggered with the button click. ~~~jsx {32-35} // create Pivot diff --git a/docs/api/internal/getreactivestate-method.md b/docs/api/internal/getreactivestate-method.md index ee1a40b..da20b22 100644 --- a/docs/api/internal/getreactivestate-method.md +++ b/docs/api/internal/getreactivestate-method.md @@ -30,17 +30,18 @@ The method returns an object with the following parameters: filters: {}, // filtering rules headerShape: {}, // table header settings predicates: {}, // available predicates by fields - limits: {} // the maximum limit for the number of rows and columns in the dataset + limits: {}, // the maximum limit for the number of rows and columns in the dataset methods: {}, // methods for data aggregation tableShape: {}, // table settings (sizes, total row, templates) tableConfig: {}, // table configuration settings (columns, data, sizes, tree mode, footer) - configPanel: boolean, // the state of the configuration panel visibility + configPanel: boolean, // the state of the configuration panel visibility + readonly: boolean, // whether the read-only mode is enabled } ~~~ ### Example -~~~jsx {22-28} +~~~jsx {21-26} // create Pivot const table = new pivot.Pivot("#root", { fields, @@ -61,12 +62,10 @@ const table = new pivot.Pivot("#root", { } }); -// output the current config state to the console -let config; -let state = table.api.getReactiveState(); +// subscribe to the reactive config store and log it on every change +const state = table.api.getReactiveState(); -if (config) { - console.log("There were some changes in Pivot config. Its current state:"); - console.log(config); -} +state.config.subscribe((config) => { + console.log("Pivot config changed. Its current state:", config); +}); ~~~ diff --git a/docs/api/internal/getstate-method.md b/docs/api/internal/getstate-method.md index 295c8a8..054d278 100644 --- a/docs/api/internal/getstate-method.md +++ b/docs/api/internal/getstate-method.md @@ -30,11 +30,12 @@ The method returns an object with the following parameters: filters: {}, // filtering rules headerShape: {}, // table header settings predicates: {}, // available predicates by fields - limits: {} // the maximum limit for the number of rows and columns in the dataset + limits: {}, // the maximum limit for the number of rows and columns in the dataset methods: {}, // methods for data aggregation tableShape: {}, // table settings (sizes, total row, templates) tableConfig: {}, // table configuration settings (columns, data, sizes, tree mode, footer) - configPanel: boolean, // the state of the configuration panel visibility + configPanel: boolean, // the state of the configuration panel visibility + readonly: boolean, // whether the read-only mode is enabled } ~~~ diff --git a/docs/api/internal/intercept-method.md b/docs/api/internal/intercept-method.md index 69b0a93..c988fa8 100644 --- a/docs/api/internal/intercept-method.md +++ b/docs/api/internal/intercept-method.md @@ -30,8 +30,8 @@ api.intercept( ### Events :::info -The full list of the Pivot internal events can be found [**here**](api/overview/main-overview.md/#pivot-events). -Use the [`api.on()`](/api/internal/on-method) method if you want to listen to the actions without modifying them. To make changes to the actions, apply the `api.intercept()` method. +The full list of the Pivot internal events can be found [**here**](api/overview/main-overview.md#pivot-events). +Use the [`api.on()`](api/internal/on-method.md) method if you want to listen to the actions without modifying them. To make changes to the actions, apply the `api.intercept()` method. ::: ### Example @@ -65,4 +65,4 @@ table.api.intercept("render-table", (ev) => { }, {tag: "render-table-tag"}); ~~~ -**Related articles**: [`render-table`](/api/events/render-table-event) +**Related articles**: [`render-table`](api/events/render-table-event.md) diff --git a/docs/api/internal/on-method.md b/docs/api/internal/on-method.md index 8e28fc4..76b8e02 100644 --- a/docs/api/internal/on-method.md +++ b/docs/api/internal/on-method.md @@ -31,15 +31,15 @@ api.on( ### Events :::info -The full list of the Pivot internal events can be found [**here**](/api/overview/main-overview/#pivot-events). -Use the `api.on()` method if you want to listen to the actions without modifying them. To make changes to the actions, apply the [`api.intercept()`](/api/internal/intercept-method) method. +The full list of the Pivot internal events can be found [**here**](api/overview/main-overview.md#pivot-events). +Use the `api.on()` method if you want to listen to the actions without modifying them. To make changes to the actions, apply the [`api.intercept()`](api/internal/intercept-method.md) method. ::: ### Example The example below shows how to output the label of a field for which the filter was activated: -~~~jsx {21-28} +~~~jsx {21-29} // create Pivot const table = new pivot.Pivot("#root", { fields, @@ -61,11 +61,12 @@ const table = new pivot.Pivot("#root", { }); table.api.on("open-filter", (ev) => { - const fieldObj = ev.field; - const field = fieldObj.base || fieldObj.field; - - if (field) { - console.log("The field for which filter was activated:", ev.field.label); + if (ev.id) { + const { config } = table.api.getState(); + const fieldObj = config[ev.area].find((f) => f.id === ev.id); + if (fieldObj) { + console.log("The field for which filter was activated:", fieldObj.label); + } } }, {tag: "open-filter-tag"}); ~~~ diff --git a/docs/api/internal/setnext-method.md b/docs/api/internal/setnext-method.md index cfe59e2..4b852ab 100644 --- a/docs/api/internal/setnext-method.md +++ b/docs/api/internal/setnext-method.md @@ -42,4 +42,4 @@ Promise.all([ }); ~~~ -**Related articles**: [`setConfig`](/api/methods/setconfig-method) +**Related articles**: [`setConfig`](api/methods/setconfig-method.md) diff --git a/docs/api/methods/gettable-method.md b/docs/api/methods/gettable-method.md index 96e861e..a2c96f4 100644 --- a/docs/api/methods/gettable-method.md +++ b/docs/api/methods/gettable-method.md @@ -10,7 +10,7 @@ description: You can learn about the getTable method in the documentation of the @short: Gets access to the underlying Table widget instance in the Pivot table -This method is used when there's a need to access the underlying Table widget instance in Pivot. It provides direct access to the Table functionality allowing for operations such as data serialization and exporting in various formats. The Table API has its own `api.exec()` method that can call the [`open-row`](/api/table/open-row), [`close-row`](/api/table/close-row), [`export`](/api/table/export), and [`filter-rows`](/api/table/filter-rows) events. +This method is used when there's a need to access the underlying Table widget instance in Pivot. It provides direct access to the Table functionality allowing for operations such as data serialization and exporting in various formats. The Table API has its own `api.exec()` method that can call the [`open-row`](api/table/open-row.md), [`close-row`](api/table/close-row.md), [`export`](api/table/export.md), and [`filter-rows`](api/table/filter-rows.md) events. ### Usage @@ -24,7 +24,7 @@ getTable(wait:boolean): Table | Promise; ### Example -In the example below we get access to the Table widget API and trigger the Table `export`event with the button click using the [`api.exec()`](/api/internal/exec-method) method. +In the example below we get access to the Table widget API and trigger the Table `export`event with the button click using the [`api.exec()`](api/internal/exec-method.md) method. ~~~jsx // create Pivot @@ -51,7 +51,7 @@ const table = new pivot.Pivot("#root", { let table_instance = table.getTable(); function toCSV() { - table_instance.exeс("export", { + table_instance.exec("export", { options: { format: "csv", cols: ";" @@ -67,9 +67,9 @@ exportButton.textContent = "Export"; document.body.appendChild(exportButton); ~~~ -**Related articles:**: +**Related articles**: -- [`close-row`](/api/table/close-row) -- [`export`](/api/table/export) -- [`filter-rows`](/api/table/filter-rows) -- [`open-row`](/api/table/open-row) \ No newline at end of file +- [`close-row`](api/table/close-row.md) +- [`export`](api/table/export.md) +- [`filter-rows`](api/table/filter-rows.md) +- [`open-row`](api/table/open-row.md) \ No newline at end of file diff --git a/docs/api/methods/setconfig-method.md b/docs/api/methods/setconfig-method.md index 1421864..86e8239 100644 --- a/docs/api/methods/setconfig-method.md +++ b/docs/api/methods/setconfig-method.md @@ -20,7 +20,7 @@ setConfig(config: { [key:any]: any }): void; ### Parameters -- `config` - (required) an object of the Pivot configuration. See the full list of properties [here](/api/overview/properties-overview) +- `config` - (required) an object of the Pivot configuration. See the full list of properties [here](api/overview/properties-overview.md) :::important The method changes only the parameters you passed. It destroys the current component and initializes a new one. diff --git a/docs/api/methods/setlocale-method.md b/docs/api/methods/setlocale-method.md index eeee017..6891bb8 100644 --- a/docs/api/methods/setlocale-method.md +++ b/docs/api/methods/setlocale-method.md @@ -52,5 +52,5 @@ table.setLocale(); // or setLocale(null); ~~~ **Related articles**: -- [Localization](/guides/localization) -- [`locale`](/api/config/locale-property) +- [Localization](guides/localization.md) +- [`locale`](api/config/locale-property.md) diff --git a/docs/api/methods/showconfigpanel-method.md b/docs/api/methods/showconfigpanel-method.md index ea5ddcf..fd01142 100644 --- a/docs/api/methods/showconfigpanel-method.md +++ b/docs/api/methods/showconfigpanel-method.md @@ -51,5 +51,5 @@ table.showConfigPanel ({ ~~~ **Related articles**: -- [`show-config-panel` event](/api/events/show-config-panel-event) -- [`configPanel` property](/api/config/configpanel-property) +- [`show-config-panel` event](api/events/show-config-panel-event.md) +- [`configPanel` property](api/config/configpanel-property.md) diff --git a/docs/api/overview/events-overview.md b/docs/api/overview/events-overview.md index 877c376..3a5be91 100644 --- a/docs/api/overview/events-overview.md +++ b/docs/api/overview/events-overview.md @@ -8,12 +8,12 @@ description: You can have Events overview of JavaScript Pivot in the documentati | Name | Description | | ------------------------------------------------- | ----------------------------------------------- | -| [](../events/add-field-event.md) | @getshort(../events/add-field-event.md) | -| [](../events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | -| [](../events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | -| [](../events/move-field-event.md) | @getshort(../events/move-field-event.md) | -| [](../events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | -| [](../events/render-table-event.md) | @getshort(../events/render-table-event.md) | -| [](../events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | -| [](../events/update-config-event.md) | @getshort(../events/update-config-event.md) | -| [](../events/update-value-event.md) | @getshort(../events/update-value-event.md) | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | diff --git a/docs/api/overview/internal-eventbus-overview.md b/docs/api/overview/internal-eventbus-overview.md index 69011d6..c5f560f 100644 --- a/docs/api/overview/internal-eventbus-overview.md +++ b/docs/api/overview/internal-eventbus-overview.md @@ -8,8 +8,8 @@ description: You can have an Internal Event Bus methods overview of JavaScript P | Name | Description | | ---------------------------------------------- | ------------------------------------------------- | -| [](../internal/detach-method.md) | @getshort(../internal/detach-method.md) | -| [](../internal/exec-method.md) | @getshort(../internal/exec-method.md) | -| [](../internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | -| [](../internal/on-method.md) | @getshort(../internal/on-method.md) | -| [](../internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | diff --git a/docs/api/overview/internal-state-overview.md b/docs/api/overview/internal-state-overview.md index 1521954..bf770d5 100644 --- a/docs/api/overview/internal-state-overview.md +++ b/docs/api/overview/internal-state-overview.md @@ -8,6 +8,6 @@ description: You can have Internal State methods overview of JavaScript Pivot in | Name | Description | | ---------------------------------------------- | -------------------------------------------------- | -| [](../internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | -| [](../internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | -| [](../internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | diff --git a/docs/api/overview/main-overview.md b/docs/api/overview/main-overview.md index 7a9373c..ef74c25 100644 --- a/docs/api/overview/main-overview.md +++ b/docs/api/overview/main-overview.md @@ -23,10 +23,10 @@ new pivot.Pivot("#root", { | Name | Description | | ------------------------------------------- | ------------------------------------------ | -| [](../methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | -| [](../methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | -| [](../methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | -| [](../methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | ## Pivot internal API @@ -34,47 +34,47 @@ new pivot.Pivot("#root", { | Name | Description | | :------------------------------------ | :------------------------------------------- | -| [](../internal/detach-method.md) | @getshort(../internal/detach-method.md) | -| [](../internal/exec-method.md) | @getshort(../internal/exec-method.md) | -| [](../internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | -| [](../internal/on-method.md) | @getshort(../internal/on-method.md) | -| [](../internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | ### State methods | Name | Description | | :---------------------------------------------- | :------------------------------------------------- | -| [](../internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | -| [](../internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | -| [](../internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | ## Pivot events | Name | Description | | :------------------------------------------------ | :---------------------------------------------- | -| [](../events/add-field-event.md) | @getshort(../events/add-field-event.md) | -| [](../events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | -| [](../events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | -| [](../events/move-field-event.md) | @getshort(../events/move-field-event.md) | -| [](../events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | -| [](../events/render-table-event.md) | @getshort(../events/render-table-event.md) | -| [](../events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | -| [](../events/update-config-event.md) | @getshort(../events/update-config-event.md) | -| [](../events/update-value-event.md) | @getshort(../events/update-value-event.md) | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | ## Pivot properties | Name | Description | | :------------------------------------------------- | :----------------------------------------------- | -| [](../config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | -| [](../config/config-property.md) | @getshort(../config/config-property.md) | -| [](../config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | -| [](../config/data-property.md) | @getshort(../config/data-property.md) | -| [](../config/fields-property.md) | @getshort(../config/fields-property.md) | -| [](../config/headershape-property.md) | @getshort(../config/headershape-property.md) | -| [](../config/limits-property.md) | @getshort(../config/limits-property.md) | -| [](../config/locale-property.md) | @getshort(../config/locale-property.md) | -| [](../config/methods-property.md) | @getshort(../config/methods-property.md) | -| [](../config/predicates-property.md) | @getshort(../config/predicates-property.md) | -| [](../config/readonly-property.md) | @getshort(../config/readonly-property.md) | -| [](../config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/docs/api/overview/methods-overview.md b/docs/api/overview/methods-overview.md index f4081e4..0ee3131 100644 --- a/docs/api/overview/methods-overview.md +++ b/docs/api/overview/methods-overview.md @@ -8,7 +8,7 @@ description: You can have Methods overview of JavaScript Pivot in the documentat | Name | Description | | ------------------------------------------- | ----------------------------------------------- | -| [](../methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | -| [](../methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | -| [](../methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | -| [](../methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | diff --git a/docs/api/overview/properties-overview.md b/docs/api/overview/properties-overview.md index 6560d51..e9612e4 100644 --- a/docs/api/overview/properties-overview.md +++ b/docs/api/overview/properties-overview.md @@ -6,19 +6,19 @@ description: You can have Properties overview of JavaScript Pivot in the documen # Properties overview -To configure **Pivot**, refer to the [Configuration](../../../guides/configuration) section. +To configure **Pivot**, refer to the [Configuration](guides/configuration.md) section. | Name | Description | | -------------------------------------------------- | ------------------------------------------------ | -| [](../config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | -| [](../config/config-property.md) | @getshort(../config/config-property.md) | -| [](../config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | -| [](../config/data-property.md) | @getshort(../config/data-property.md) | -| [](../config/fields-property.md) | @getshort(../config/fields-property.md) | -| [](../config/headershape-property.md) | @getshort(../config/headershape-property.md) | -| [](../config/limits-property.md) | @getshort(../config/limits-property.md) | -| [](../config/locale-property.md) | @getshort(../config/locale-property.md) | -| [](../config/methods-property.md) | @getshort(../config/methods-property.md) | -| [](../config/predicates-property.md) | @getshort(../config/predicates-property.md) | -| [](../config/readonly-property.md) | @getshort(../config/readonly-property.md) | -| [](../config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/docs/api/overview/table-events-overview.md b/docs/api/overview/table-events-overview.md index 89495be..89d48c1 100644 --- a/docs/api/overview/table-events-overview.md +++ b/docs/api/overview/table-events-overview.md @@ -6,11 +6,11 @@ description: You can have Table events overview of JavaScript Pivot in the docum # Table events overview -The [`getTable`](/api/methods/gettable-method) method of the Pivot API allows getting access to the underlying Table widget instance inside Pivot and execute the next Table events: +The [`getTable`](api/methods/gettable-method.md) method of the Pivot API allows getting access to the underlying Table widget instance inside Pivot and execute the next Table events: | Name | Description | | ------------------------------------------------- | ----------------------------------------------- | -| [](../table/close-row.md) | @getshort(../table/close-row.md) | -| [](../table/export.md) | @getshort(../table/export.md) | -| [](../table/filter-rows.md) | @getshort(../table/filter-rows.md) | -| [](../table/open-row.md) | @getshort(../table/open-row.md) | +| [](api/table/close-row.md) | @getshort(../table/close-row.md) | +| [](api/table/export.md) | @getshort(../table/export.md) | +| [](api/table/filter-rows.md) | @getshort(../table/filter-rows.md) | +| [](api/table/open-row.md) | @getshort(../table/open-row.md) | diff --git a/docs/api/table/close-row.md b/docs/api/table/close-row.md index a6e41f8..574073b 100644 --- a/docs/api/table/close-row.md +++ b/docs/api/table/close-row.md @@ -10,7 +10,7 @@ description: You can learn about the close-row event in the documentation of the @short: Fires when closing (collapsing) a row -To trigger the Table event, it's necessary to get access to the underlying Table widget instance inside Pivot via the [`getTable`](/api/methods/gettable-method) method. The tree mode should be enabled via the [`tableShape`](/api/config/tableshape-property) property. +To trigger the Table event, it's necessary to get access to the underlying Table widget instance inside Pivot via the [`getTable`](api/methods/gettable-method.md) method. The tree mode should be enabled via the [`tableShape`](api/config/tableshape-property.md) property. ### Usage @@ -39,6 +39,6 @@ The snippet below demonstrates how to open/close all rows with a button click: **Related articles**: -- [`getTable`](/api/methods/gettable-method) -- [Expanding/collapsing all rows](/guides/configuration/#expandingcollapsing-all-rows) +- [`getTable`](api/methods/gettable-method.md) +- [Expanding/collapsing all rows](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/docs/api/table/export.md b/docs/api/table/export.md index 014bf2a..0653a71 100644 --- a/docs/api/table/export.md +++ b/docs/api/table/export.md @@ -10,7 +10,7 @@ description: You can learn about the export event in the documentation of the DH @short: Fires when exporting data -To trigger the Table event, it's necessary to get access to the Table instance inside Pivot via the [`getTable`](/api/methods/gettable-method) method. +To trigger the Table event, it's necessary to get access to the Table instance inside Pivot via the [`getTable`](api/methods/gettable-method.md) method. ### Usage @@ -61,7 +61,7 @@ The `export` action of the Table widget has the next parameters that you can con - `options` - an object with the export options; options differ depending on the format type - `result` - the result of the exported Excel or CSV data (usually Blob or file depending on the `download` option) - **Common options for both formats ("csv" "xlsx" ):** + **Common options for both formats ("csv" "xlsx" )**: - `format` (string) - (optional) the export format that can be "csv" or "xlsx" - `fileName` (string) - (optional) a file name ("data" by default) @@ -69,7 +69,7 @@ The `export` action of the Table widget has the next parameters that you can con - `footer` (boolean) - (optional) defines if a footer should be exported (**true** by default) - `download` (boolean) - (optional) defines whether to download a file. **true** is set by default. If set to **false**, the file will not be downloaded, Excel or CSV data (Blob) will be available as `ev.result` - **Options specific for "xlsx" format:** + **Options specific for "xlsx" format**: - `sheetName` (string) - a name of Excel sheet ( "data" by default) - `styles` (boolean or object) - if set to **false**, grid will be exported without any styling; can be configured using a hash of style properties: @@ -89,10 +89,10 @@ The `export` action of the Table widget has the next parameters that you can con - `cellStyle` - a function that allows customizing the style and format of individual cells during export. It takes the value, row, and column objects as parameters and should return an object with style properties (e.g., alignment or format) - `headerCellStyle` - similar to cellStyle, but specifically for the header and footer cells. This function takes the text, header cell object, column object, and type ("header" or "footer") and returns style properties :::note - By default, for the "xlsx" format, date and number fields are exported as raw values with default format or the format defined via the [`fields`](/api/config/fields-property) property. But if a template is defined for a field (see the [`tableShape`](/api/config/tableshape-property) property), it exports the rendered value defined by that template. In case both the template and `format` are set, the template settings will override the format ones. + By default, for the "xlsx" format, date and number fields are exported as raw values with default format or the format defined via the [`fields`](api/config/fields-property.md) property. But if a template is defined for a field (see the [`tableShape`](api/config/tableshape-property.md) property), it exports the rendered value defined by that template. In case both the template and `format` are set, the template settings will override the format ones. ::: - **Options specific for "csv" format:** + **Options specific for "csv" format**: - `rows` (string) - (optional) rows delimiter, "\n" by default - `cols` (string) - (optional) columns delimiter, "\t" by default @@ -104,7 +104,7 @@ In this snippet you can see how to export data: **Related articles**: -- [`getTable`](/api/methods/gettable-method) -- [Exporting data](/guides/exporting-data) -- [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields) +- [`getTable`](api/methods/gettable-method.md) +- [Exporting data](guides/exporting-data.md) +- [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields) diff --git a/docs/api/table/filter-rows.md b/docs/api/table/filter-rows.md index 1bf5513..af9fb0e 100644 --- a/docs/api/table/filter-rows.md +++ b/docs/api/table/filter-rows.md @@ -10,7 +10,7 @@ description: You can learn about the filter-rows event in the documentation of t @short: Fires when filtering data -To trigger the Table event, it's necessary to get access to the Table instance inside Pivot via the [`getTable`](/api/methods/gettable-method) method. +To trigger the Table event, it's necessary to get access to the Table instance inside Pivot via the [`getTable`](api/methods/gettable-method.md) method. ### Usage @@ -32,6 +32,4 @@ The snippet below demonstrates how to filter aggregated (visible) data in the ta - -**Related article**: [`getTable`](/api/methods/gettable-method) - +**Related article**: [`getTable`](api/methods/gettable-method.md) diff --git a/docs/api/table/open-row.md b/docs/api/table/open-row.md index 7e93ebf..5793df0 100644 --- a/docs/api/table/open-row.md +++ b/docs/api/table/open-row.md @@ -10,7 +10,7 @@ description: You can learn about the close-row event in the documentation of the @short: Fires when opening (expanding) a row -To trigger the Table event, it's necessary to get access to the Table instance inside Pivot via the [`getTable`](/api/methods/gettable-method) method. The tree mode should be enabled via the [`tableShape`](/api/config/tableshape-property) property. +To trigger the Table event, it's necessary to get access to the Table instance inside Pivot via the [`getTable`](api/methods/gettable-method.md) method. The tree mode should be enabled via the [`tableShape`](api/config/tableshape-property.md) property. ### Usage @@ -39,5 +39,5 @@ The snippet below demonstrates how to open/close all rows with a button click: **Related articles**: -- [`getTable`](/api/methods/gettable-method) -- [Expanding/collapsing all rows](/guides/configuration/#expandingcollapsing-all-rows) \ No newline at end of file +- [`getTable`](api/methods/gettable-method.md) +- [Expanding/collapsing all rows](guides/configuration.md#expandingcollapsing-all-rows) \ No newline at end of file diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 70a66c2..1f6437e 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -6,34 +6,34 @@ description: You can learn about the configuration in the documentation of the D # Configuration -You can configure Pivot appearance and functionality via the corresponding API, namely, you can configure the Pivot table elements and the configuration panel. The available parameters will allow you to: +Configure the Pivot table and the Configuration panel through the following API: -- define the structure of the Pivot table and how data is aggregated via the [`config`](/api/config/config-property) property -- change the table configuration on the fly via the [`render-table`](/api/events/render-table-event) event -- configure the look of the Pivot table via the [`tableShape`](/api/config/tableshape-property) property -- configure the look and behavior of the Pivot columns via the [`columnShape`](/api/config/columnshape-property) property -- configure the look and behavior of headers in the Pivot table via the [`headerShape`](/api/config/headershape-property) property -- control the visibility of the configuration panel via the [`configPanel`](/api/config/configpanel-property) property -- apply the desired locale via the [`setLocale()`](/api/methods/setlocale-method) method (see the [Localization](/guides/localization) section) -- load data and fields via the corresponding [`data`](/api/config/data-property) and [`fields`](/api/config/fields-property) properties -- define how data should be modified before it's applied via the [`predicates`](/api/config/predicates-property) property -- define custom mathematical methods for data aggregation via the [`methods`](/api/config/methods-property) property -- control the maximum limit for the number of rows and columns in the final dataset via the [`limits`](/api/config/limits-property) property +- [`config`](api/config/config-property.md) — define the structure of the Pivot table and how data is aggregated +- [`render-table`](api/events/render-table-event.md) — change the table configuration on the fly +- [`tableShape`](api/config/tableshape-property.md) — configure the look of the Pivot table +- [`columnShape`](api/config/columnshape-property.md) — configure the look and behavior of columns +- [`headerShape`](api/config/headershape-property.md) — configure the look and behavior of headers +- [`configPanel`](api/config/configpanel-property.md) — control the visibility of the Configuration panel +- [`setLocale`](api/methods/setlocale-method.md) — apply a locale (see [Localization](guides/localization.md)) +- [`data`](api/config/data-property.md), [`fields`](api/config/fields-property.md) — load data and field metadata +- [`predicates`](api/config/predicates-property.md) — pre-process data before aggregation +- [`methods`](api/config/methods-property.md) — define custom aggregation methods +- [`limits`](api/config/limits-property.md) — cap the number of rows and columns in the final dataset -All instructions about working with data see here: [Working with data](/guides/working-with-data) +For instructions on working with data, see [Working with data](guides/working-with-data.md). -You can configure and/or customize the following elements of the Pivot table: +You can configure the following Pivot table elements: - columns and rows - headers and footers - cells -- the table sizes +- table sizes -## Resizing the table +## Resize the table {#resizing-the-table} -You can change the size of the table rows and columns, header and footer using the [`tableShape`](/api/config/tableshape-property) property. +Use the [`tableShape`](api/config/tableshape-property.md) property to change the size of rows, columns, header, and footer. -The next sizes are applied by default: +The following code snippet shows the default sizes: ~~~jsx const sizes = { @@ -44,7 +44,7 @@ const sizes = { }; ~~~ -Example: +The following code snippet overrides the default sizes: ~~~jsx {4-11} const table = new pivot.Pivot("#root", { @@ -76,22 +76,21 @@ const table = new pivot.Pivot("#root", { ~~~ :::info -To set the width of specific column(s), apply the `width` parameter of the [columnShape property](/api/config/columnshape-property). +To set the width of specific columns, use the `width` parameter of the [`columnShape`](api/config/columnshape-property.md) property. ::: -## Autosizing columns to content +## Autosize columns to content -The widget allows setting the minimum width value for all columns and it also enables sizing for the table data only, the table header or combined auto sizing. To configure all these autosizing settings, you should apply the `autoWidth` parameter of the [`columnShape`](/api/config/columnshape-property) property. +Use the `autoWidth` parameter of the [`columnShape`](api/config/columnshape-property.md) property to calculate column widths automatically. All `autoWidth` sub-parameters are optional — for full descriptions see the [`columnShape`](api/config/columnshape-property.md) reference. -All parameters of `autoWidth` are optional and for detailed description of each parameter refer to the [columnShape](/api/config/columnshape-property) property. +The `autoWidth` object accepts the following parameters: -- use the `columns` parameter to define if the width of columns should be calculated automatically and which columns will be affected -- use the `auto` parameter to adjust the width to the header or cell content (or both) -- use `maxRows` to specify how many data rows will be applied to detect the size of a column; by default 20 rows are used +- `columns` — object that selects which fields receive auto-calculated width +- `auto` — adjusts the width to the header, the cell content, or both +- `maxRows` — number of data rows analyzed to detect column size (default: 20) +- `firstOnly` — if `true` (default), analyzes each field only once. When multiple columns are based on the same field (e.g., `oil` with `count` and `oil` with `sum`), only the first column is analyzed and the others inherit its width -If `firstOnly` is set to **true** (default), each field of the same data is analyzed only once to calculate the column width. In case of multiple columns based on the same data (e.g., the *oil* field with the *count* operation and the *oil* field with the *sum* operation), only data in the first one will be analyzed and the others will inherit this width. - -Example: +The following code snippet enables `autoWidth` for four fields and disables `firstOnly` so every column gets its own measurement: ~~~jsx {18-30} const table = new pivot.Pivot("#root", { @@ -127,13 +126,13 @@ const table = new pivot.Pivot("#root", { }); ~~~ -## Applying templates to cells +## Apply templates to cells {#applying-templates-to-cells} -### Adding templates via tableShape +### Add templates via tableShape -To set a template to cells, use the `templates` parameter of the [`tableShape`](/api/config/tableshape-property) property. It's an object where each key is a field id and the value is a function that returns a string. All columns based on the specified field will have the related template applied. +Use the `templates` parameter of the [`tableShape`](api/config/tableshape-property.md) property to render cell values through a function. Each key is a field ID and each value is a function that returns a string. All columns based on the specified field receive the template. -In the example below we apply the template to the *state* cells to show the combined name of a state (the full name and abbreviation). +The example below applies a template to `state` cells that shows the combined name of a state (full name plus abbreviation): ~~~jsx {10-15} const states = { @@ -141,14 +140,14 @@ const states = { "Colorado": "CO", "Connecticut": "CT", "Florida": "FL", -// other values, + // other values }; const table = new pivot.Pivot("#root", { tableShape: { templates: { - // set a template to customize values of "state" cells - state: v => v+ ` (${states[v]})`, + // customize values of "state" cells + state: v => v + ` (${states[v]})`, } }, fields, @@ -172,11 +171,11 @@ const table = new pivot.Pivot("#root", { }); ~~~ -### Adding a template via the template helper +### Add a template via the template helper {#adding-a-template-via-the-template-helper} -You can insert HTML content to table cells via the [`pivot.template`](/api/helpers/template) helper by defining a template as a `cell` property of the `column` object. You need to apply the template right before the table renders, which is done by intercepting the [render-table](/api/events/render-table-event) event using the [api.intercept()](/api/internal/intercept-method) method. +To insert HTML content into body cells, use the [`pivot.template`](api/helpers/template.md) helper and assign the result to the `cell` property of the column object. Apply the template right before the table renders by intercepting the [`render-table`](api/events/render-table-event.md) event with the [`api.intercept`](api/internal/intercept-method.md) method. -The example shows how you can add icons (star or flag icon) to body cells based on their field (id, user_score): +The example below adds icons (star or flag) to body cells based on the field (`id`, `user_score`): ~~~js function cellTemplate(value, method, row, column) { @@ -205,7 +204,7 @@ function scoreTemplate(value) { widget.api.intercept("render-table", ({ config: tableConfig }) => { tableConfig.columns = tableConfig.columns.map((c) => { if (c.area === "rows") { - // Apply a template to column cells from the "rows" area + // apply a template to column cells from the "rows" area c.cell = pivot.template(({ value, method, row, column }) => cellTemplate(value, method, row, column)); } return c; @@ -213,19 +212,25 @@ widget.api.intercept("render-table", ({ config: tableConfig }) => { }); ~~~ -## Applying templates to headers +## Apply templates to headers {#applying-templates-to-headers} + +### Add templates via headerShape -### Adding templates via headerShape +To control the text format in headers, use the `template` parameter of the [`headerShape`](api/config/headershape-property.md) property. The parameter is a function that: -To define the format of text in headers, apply the `template` parameter of the [`headerShape`](/api/config/headershape-property) property. The parameter is the function that: +- takes the field label, ID, and sublabel (the method name, if any) +- returns the processed value -- takes the field id, label and sublabel (the name of a method if any is applied) -- returns the processed value +The default template is: + +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ -A default template is as follows: *template: (label, id, subLabel) => label + (subLabel ? `(${subLabel})` : "")*. By default, for the fields applied as values the label and method are shown (e.g., *Oil(count)*). -If no other template is applied to columns, the value of the `label` parameter is displayed. If any [`predicates`](/api/config/predicates-property) template is applied, it will override the template of the `headerShape` property. +Without a custom template, `values`-area fields display the label and method (e.g., `Oil(count)`), and other-area fields display the `label` value. A [`predicates`](api/config/predicates-property.md) template overrides the `headerShape` template. -In the example below for the **values** fields the header will display the label, the method name (subLabel) and converts the result to lowercase (e.g., *profit (sum)*): +The example below converts header text to lowercase, producing labels such as `profit (sum)`: ~~~jsx {3-6} new pivot.Pivot("#pivot", { @@ -253,14 +258,14 @@ new pivot.Pivot("#pivot", { }); ~~~ -### Adding templates via the template helper +### Add templates via the template helper -You can insert HTML content to header cells via the [`pivot.template`](/api/helpers/template) helper by defining a template as a `cell` property of the header cell object. You need to apply the template right before the table renders, which is done by intercepting the [render-table](/api/events/render-table-event) event using the [api.intercept()](/api/internal/intercept-method) method. +To insert HTML content into header cells, use the [`pivot.template`](api/helpers/template.md) helper and assign the result to the `cell` property of the header cell object. Apply the template right before the table renders by intercepting the [`render-table`](api/events/render-table-event.md) event with the [`api.intercept`](api/internal/intercept-method.md) method. -The example below shows how to add icons to: +The example below adds icons to: -- the header labels based on the field name (for example, if the field is "id", it adds the globe icon next to the header value) -- the column headers based on the value (colored arrow indicators are added) +- header labels based on the field name (for example, `id` gets a globe icon) +- column headers based on cell value (colored arrow indicators based on the `status` value) ~~~jsx function rowsHeaderTemplate(value, field) { @@ -280,10 +285,10 @@ function statusTemplate(value) { widget.api.intercept("render-table", ({ config: tableConfig }) => { tableConfig.columns = tableConfig.columns.map((c) => { if (c.area === "rows") { - // Apply a template to the first header row of the columns from the "rows" area + // apply a template to the first header row of columns from the "rows" area c.header[0].cell = pivot.template(({ value, field }) => rowsHeaderTemplate(value, field)); } else { - // For header cells that display values from the "status" field + // header cells that display values from the "status" field const headerCell = c.header.find((h) => h.field === "status"); if (headerCell) { headerCell.cell = pivot.template(({ value }) => statusTemplate(value)); @@ -294,9 +299,11 @@ widget.api.intercept("render-table", ({ config: tableConfig }) => { }); ~~~ -## Making columns collapsible +## Make columns collapsible + +To allow users to collapse and expand columns under a shared header, set the `collapsible` parameter of the [`headerShape`](api/config/headershape-property.md) property to `true`. -It's possible to collapse/expand columns that are under one header. To make columns collapsible, use the value of the `collapsible` parameter of the [`headerShape`](/api/config/headershape-property) property by setting it to **true**. +The following code snippet enables collapsible header columns: ~~~jsx {4-6} const table = new pivot.Pivot("#root", { @@ -322,13 +329,15 @@ const table = new pivot.Pivot("#root", { }); ~~~ -## Freezing columns +## Freeze columns {#freezing-columns} -The widget allows freezing columns on the left or right side, which makes the columns static and visible while scrolling. To freeze columns, apply the **split** parameter of the [`tableShape`](/api/config/tableshape-property) property by setting the value of the `left` or `right` parameter to **true**. More details with examples, see below. +Freeze columns on the left or the right so they stay visible while the rest of the table scrolls. Use the `split` parameter of the [`tableShape`](api/config/tableshape-property.md) property and set `left` or `right` to `true`. -### Freezing columns on the left +### Freeze columns on the left -The number of columns that are split is equal to the number of the rows fields that are defined in the [`config`](/api/config/config-property) property. In the **tree** mode only one column gets frozen regardless of the number of the rows fields that are defined. In the sample below, 1 column is fixed initially on the left, which is equal to the number of fields defined for the "rows" area. +When `split.left` is `true`, the number of frozen columns equals the number of `rows` fields in the [`config`](api/config/config-property.md) property. In tree mode, only one column is frozen regardless of the `rows` field count. + +The following code snippet freezes one column on the left (one `rows` field is defined): ~~~jsx {19} const table = new pivot.Pivot("#root", { @@ -354,11 +363,11 @@ const table = new pivot.Pivot("#root", { }); ~~~ -You can also apply a custom split using the [`render-table`](/api/events/render-table-event) event. It's not recommended to split columns with colspans. +To set a custom split count, listen to the [`render-table`](api/events/render-table-event.md) event and override `tableConfig.split`. Avoid splitting columns with colspans. -In the sample below all columns from the "rows" area and first 4 columns from the "values" area are fixed initially. The number of columns that are split depends on the number of the rows and values fields that are defined via the [`config`](/api/config/config-property) property. +The following code snippet freezes all `rows` columns plus twice the number of `values` fields on the left: -~~~jsx {19-25} +~~~jsx {19-26} const table = new pivot.Pivot("#root", { fields, data, @@ -377,8 +386,8 @@ const table = new pivot.Pivot("#root", { ] } }); -table.api.on("render-table", (tableConfig) => { - const config = api.getState().config; +table.api.on("render-table", ({ config: tableConfig }) => { + const { config } = table.api.getState(); tableConfig.split = { left: config.rows.length + config.values.length * 2 @@ -386,9 +395,11 @@ table.api.on("render-table", (tableConfig) => { }); ~~~ -### Freezing columns on the right +### Freeze columns on the right {#freezing-columns-on-the-right} + +Set `split.right` to `true` to freeze total columns on the right. -The `right` parameter of the [`tableShape`](/api/config/tableshape-property) property allows fixing total columns on the right. +The following code snippet freezes the total column on the right: ~~~jsx {4-7} const widget = new pivot.Pivot("#pivot", { @@ -415,7 +426,9 @@ const widget = new pivot.Pivot("#pivot", { }); ~~~ -To fix custom columns on the right, you need to apply the table API via the [`render-table`](/api/events/render-table-event) event. It's not recommended to split columns with colspans. In the sample below, 2 columns on the right are fixed initially. +To freeze a custom number of columns on the right, listen to the [`render-table`](api/events/render-table-event.md) event and override `tableConfig.split`. Avoid splitting columns with colspans. + +The following code snippet freezes as many columns on the right as there are `values` fields: ~~~jsx {20-25} const widget = new pivot.Pivot("#pivot", { @@ -445,9 +458,11 @@ widget.api.on("render-table", ({ config: tableConfig }) => { }) ~~~ -## Sorting in columns +## Sort in columns + +Sorting in the UI is enabled by default — users click a column header to sort. To disable it, set the `sort` parameter of the [`columnShape`](api/config/columnshape-property.md) property to `false`. -The sorting functionality is enabled by default. A user can click the column's header to sort data. To disable/enable sorting, apply the `sort` parameter of the [`columnShape`](/api/config/columnshape-property) property. In the example below we disable sorting. +The following code snippet disables UI sorting: ~~~jsx {19} const table = new pivot.Pivot("#root", { @@ -473,12 +488,13 @@ const table = new pivot.Pivot("#root", { }); ~~~ -For more information about sorting data, refer to [Sorting data](/guides/working-with-data#sorting-data). +For more on default sort, custom comparators, and runtime updates, see [Sort data](guides/working-with-data.md#sorting-data). -## Enabling the tree mode +## Enable tree mode {#enabling-the-tree-mode} -The widget allows presenting data in a hierarchical format with expandable rows. To switch to the tree mode, apply the `tree` parameter of the [`tableShape`](/api/config/tableshape-property) property by setting its value to **true** (default is **false**). -To specify the parent row, put its name first in the `rows` array of the [`config`](/api/config/config-property) property. +Tree mode presents data hierarchically with expandable rows. Set the `tree` parameter of the [`tableShape`](api/config/tableshape-property.md) property to `true` (default `false`). The first field of the `rows` array in [`config`](api/config/config-property.md) becomes the parent row. + +The following code snippet enables tree mode with `studio` as the parent and `genre` as nested rows: ~~~jsx {3} const table = new pivot.Pivot("#root", { @@ -515,11 +531,11 @@ const table = new pivot.Pivot("#root", { }); ~~~ -## Expanding/collapsing all rows +## Expand or collapse all rows {#expandingcollapsing-all-rows} -To expand/collapse all rows, the **tree** mode should be enabled via the [`tableShape`](/api/config/tableshape-property) property and you should use the [`close-row`](/api/table/close-row) and [`open-row`](/api/table/open-row) events of the Table widget getting access to its API via the [`getTable`](/api/methods/gettable-method) method. +To expand or collapse all rows programmatically, enable tree mode via the [`tableShape`](api/config/tableshape-property.md) property. Then access the Table widget instance with the [`getTable`](api/methods/gettable-method.md) method and trigger the [`open-row`](api/table/open-row.md) or [`close-row`](api/table/close-row.md) event through the Table's `api.exec` method. -The example below shows how to expand/collapse all data rows with the button click in the table tree mode. +The example below renders Open all and Close all buttons that expand or collapse every branch in tree mode: ~~~jsx const table = new pivot.Pivot("#root", { @@ -553,21 +569,21 @@ const table = new pivot.Pivot("#root", { }); const api = table.api; -const table = api.getTable(); -// setting all table branches closed on the table config update +const tableInstance = api.getTable(); +// keep all table branches closed on render api.intercept("render-table", (ev) => { ev.config.data.forEach((r) => (r.open = false)); - // returning "false" here will prevent the table from rendering + // return false here to prevent the table from rendering // return false; }); function openAll() { - table.exec("open-row", { id: 0, nested: true }); + tableInstance.exec("open-row", { id: 0, nested: true }); } function closeAll() { - table.exec("close-row", { id: 0, nested: true }); + tableInstance.exec("close-row", { id: 0, nested: true }); } const openAllButton = document.createElement("button"); @@ -582,9 +598,11 @@ document.body.appendChild(openAllButton); document.body.appendChild(closeAllButton); ~~~ -## Changing text orientation in headers +## Change header text orientation + +To rotate header text from horizontal to vertical, set the `vertical` parameter of the [`headerShape`](api/config/headershape-property.md) property to `true`. -To change text orientation from default horizontal to vertical, use the [`headerShape`](/api/config/headershape-property) property and set its `vertical` parameter to **true**. +The following code snippet renders vertical header text: ~~~jsx {4-6} const table = new pivot.Pivot("#root", { @@ -610,13 +628,15 @@ const table = new pivot.Pivot("#root", { }); ~~~ -## Controlling visibility of Configuration panel +## Control Configuration panel visibility {#controlling-visibility-of-configuration-panel} -The Configuration panel is displayed by default. The widget provides the default functionality that allows controlling the visibility of the Configuration panel with the button click. It's made possible via the [`configPanel`](/api/config/configpanel-property) property or [`show-config-panel`](/api/events/show-config-panel-event) event. +The Configuration panel appears by default. Users can toggle it through the **Hide Settings** / **Show Settings** button. Control the panel programmatically through the [`configPanel`](api/config/configpanel-property.md) property, the [`show-config-panel`](api/events/show-config-panel-event.md) event, or the [`showConfigPanel`](api/methods/showconfigpanel-method.md) method. -### Hiding Configuration panel +### Hide the Configuration panel -To hide the panel, set the value of the [`configPanel`](/api/config/configpanel-property) property to **false**. +To hide the panel on initialization, set the [`configPanel`](api/config/configpanel-property.md) property to `false`. + +The following code snippet initializes Pivot with the panel hidden: ~~~jsx // the configuration panel is hidden on init @@ -641,7 +661,9 @@ const table = new pivot.Pivot("#root", { }); ~~~ -You can also trigger the [`show-config-panel`](/api/events/show-config-panel-event) event with the [`api.exec()`](/api/internal/exec-method) method, and set the `mode` parameter to **false**. +To toggle the panel at runtime, trigger the [`show-config-panel`](api/events/show-config-panel-event.md) event with the [`api.exec`](api/internal/exec-method.md) method and set the `mode` parameter to `false`. + +The following code snippet hides the panel after initialization: ~~~jsx {19-22} const table = new pivot.Pivot("#root", { @@ -662,17 +684,17 @@ const table = new pivot.Pivot("#root", { ] } }); -//hide the configuration panel +// hide the configuration panel table.api.exec("show-config-panel", { mode: false }); ~~~ -### Disabling the default toggling functionality +### Disable the default toggling -You can block toggling the visibility of the Configuration panel on the button click via the [`api.intercept()`](/api/internal/intercept-method) method (by listening to the [`show-config-panel`](/api/events/show-config-panel-event) event and returning *false*). +To block the default toggle button entirely, intercept the [`show-config-panel`](api/events/show-config-panel-event.md) event with the [`api.intercept`](api/internal/intercept-method.md) method and return `false`. -Example: +The following code snippet disables the toggle button: ~~~jsx {20-22} const table = new pivot.Pivot("#root", { @@ -699,22 +721,20 @@ table.api.intercept("show-config-panel", () => { }); ~~~ -You can also control the visibility of the Configuration panel using the [`showConfigPanel()`](/api/methods/showconfigpanel-method) method. +For an alternative API, use the [`showConfigPanel`](api/methods/showconfigpanel-method.md) method. ### Actions with fields in the panel -In the Configuration panel it's possible to perform the next operations with fields: +The Configuration panel supports the following field operations: -- [add-field](/api/events/add-field-event) -- [delete-field](/api/events/delete-field-event) -- [update-field](/api/events/update-value-event) -- [move-field](/api/events/move-field-event) +- [`add-field`](api/events/add-field-event.md) — add a field to an area +- [`delete-field`](api/events/delete-field-event.md) — remove a field from an area +- [`update-field`](api/events/update-field-event.md) — update a field's method or settings +- [`move-field`](api/events/move-field-event.md) — reorder fields within an area -**Related samples:** +**Related samples**: - [Pivot 2. Adding text templates for table and header cells](https://snippet.dhtmlx.com/n9ylp6b2) - [Pivot 2. Custom frozen (fixed) columns (your number)](https://snippet.dhtmlx.com/53erlmgp) - [Pivot 2. Expand and collapse all rows](https://snippet.dhtmlx.com/i4mi6ejn) - [Pivot 2. Frozen(fixed) columns on the left and right](https://snippet.dhtmlx.com/lahf729o) - [Pivot 2. Sorting](https://snippet.dhtmlx.com/j7vtief6) - - diff --git a/docs/guides/exporting-data.md b/docs/guides/exporting-data.md index effed77..c43d7de 100644 --- a/docs/guides/exporting-data.md +++ b/docs/guides/exporting-data.md @@ -6,34 +6,40 @@ description: You can explore how to export data in the documentation of the DHTM # Exporting data -To export the table data to the XLSX or CSV format, it's necessary to get access to the underlying Table widget instance inside Pivot and apply its API to export data. To do this, you should use the [`getTable`](/api/methods/gettable-method) method and execute the [`export`](/api/table/export) event. +Pivot exports table data in XLSX or CSV format through the underlying Table widget. Access the Table instance with the [`getTable`](api/methods/gettable-method.md) method, then trigger the [`export`](api/table/export.md) event with the Table's [`api.exec`](api/internal/exec-method.md) method. -In the example below we get access to the Table instance and trigger the `export`action using the [`api.exec()`](/api/internal/exec-method) method. +The example below accesses the Table instance and triggers the `export` event in CSV and XLSX formats: ~~~jsx -const widget = new pivot.Pivot("#root", { /*setting*/}); -widget.api.getTable().exec("export", { - options: { - format: "csv", - cols: ";" - } +const widget = new pivot.Pivot("#root", { /* settings */ }); + +widget.getTable().exec("export", { + options: { + format: "csv", + cols: ";" + } }); -widget.api.getTable().exec("export", { - options: { - format: "xlsx", - fileName: "My Report", - sheetName: "Quarter 1", - } + +widget.getTable().exec("export", { + options: { + format: "xlsx", + fileName: "My Report", + sheetName: "Quarter 1" + } }); ~~~ +:::tip +The [`getTable`](api/methods/gettable-method.md) method accepts an optional `wait` boolean parameter. Pass `true` to receive a promise that resolves once the Table API is available. Useful when the Table API must be ready during Pivot initialization. +::: + ## Example -In this snippet you can see how to export data: +The snippet below exports data: **Related articles**: -- [Date formatting](/guides/localization#date-formatting) -- [`export`](/api/table/export) \ No newline at end of file +- [Date formatting](guides/localization.md#date-formatting) +- [`export`](api/table/export.md) diff --git a/docs/guides/initialization.md b/docs/guides/initialization.md index a7252f8..c1f33c8 100644 --- a/docs/guides/initialization.md +++ b/docs/guides/initialization.md @@ -6,47 +6,49 @@ description: You can learn about the initialization in the documentation of the # Initialization -This guide will give you detailed instructions on how to create Pivot on a page to enrich your application with features of the Pivot table. Take the following steps to get a ready-to-use component: +This guide explains how to create Pivot on a page and enrich your application with Pivot table features. Take the following steps to get a ready-to-use component: -1. [Include the Pivot source files on a page](#including-source-files). -2. [Create a container for Pivot](#creating-container). -3. [Initialize Pivot with a constructor](#initializing-pivot). +1. [Include the Pivot source files on a page](#include-source-files). +2. [Create a container for Pivot](#create-a-container). +3. [Initialize Pivot with a constructor](#initialize-pivot). -## Including source files +## Include source files -See also how to download packages: [Downloading packages](/how-to-start#step-1-downloading-and-installing-packages). +A Pivot app requires two source files on the page. For instructions on downloading the package, see [Downloading packages](how-to-start.md#step-1-downloading-and-installing-packages). -To create a Pivot app, you need to include 2 source files on your page: +Include the following files: - *pivot.js* - *pivot.css* -Make sure that you set correct relative paths to the source files: +Set the correct relative paths to the source files: ~~~html title="index.html" ~~~ -## Creating container +## Create a container -Add a container for Pivot and give it an ID, for example *"root"*: +Pivot renders into an HTML container element. Add a container and assign an ID, for example *"root"*: ~~~html title="index.html"
~~~ -## Initializing Pivot +## Initialize Pivot -Initialize Pivot with the **pivot.Pivot** constructor. It takes two parameters: +The `pivot.Pivot` constructor takes two parameters: -- an HTML container (the ID of the HTML container) +- the ID of the HTML container - an object with configuration properties +The following code snippet creates a Pivot instance in the *"root"* container with initial fields, data, and structure: + ~~~jsx // create Pivot const table = new pivot.Pivot("#root", { - //configuration properties + // configuration properties fields, data, config: { @@ -62,14 +64,23 @@ const table = new pivot.Pivot("#root", { }); ~~~ +The constructor returns a Pivot instance. Call API methods on the returned instance: + +- [`getTable`](api/methods/gettable-method.md) — get access to the underlying Table widget instance +- [`setConfig`](api/methods/setconfig-method.md) — update the current Pivot configuration +- [`setLocale`](api/methods/setlocale-method.md) — apply a new locale to Pivot +- [`showConfigPanel`](api/methods/showconfigpanel-method.md) — show or hide the Configuration panel + ## Configuration properties +The Pivot constructor accepts an object with configuration properties that control data, layout, and behavior. + :::info -The full list of properties to configure **Pivot** can be found [**here**](api/overview/properties-overview.md). +For the full list of properties to configure Pivot, see [Properties overview](api/overview/properties-overview.md). ::: ## Example -In this snippet you can see how to initialize **Pivot** with the initial data: +The snippet below initializes Pivot with the initial data: diff --git a/docs/guides/integration-with-angular.md b/docs/guides/integration-with-angular.md index f043e0d..a645503 100644 --- a/docs/guides/integration-with-angular.md +++ b/docs/guides/integration-with-angular.md @@ -7,79 +7,81 @@ description: You can learn about the integration with Angular in the documentati # Integration with Angular :::tip -You should be familiar with basic concepts and patterns of **Angular** before reading this documentation. To refresh your knowledge, please refer to the [**Angular documentation**](https://v17.angular.io/docs). +Familiarity with the basic concepts and patterns of **Angular** is assumed. To refresh, see the [**Angular documentation**](https://v17.angular.io/docs). ::: -DHTMLX Pivot is compatible with **Angular**. We have prepared code examples on how to use DHTMLX Pivot with **Angular**. For more information, refer to the corresponding [**Example on GitHub**](https://github.com/DHTMLX/angular-pivot-demo). +DHTMLX Pivot integrates with **Angular** as a regular component. For a full working setup, see the [**Angular Pivot demo on GitHub**](https://github.com/DHTMLX/angular-pivot-demo). -## Creating a project +## Create a project :::info -Before you start to create a new project, install [**Angular CLI**](https://v1.angular.io/cli) and [**Node.js**](https://nodejs.org/en/). +Install [**Angular CLI**](https://v1.angular.io/cli) and [**Node.js**](https://nodejs.org/en/) before you start. ::: -Create a new **my-angular-pivot-app** project using Angular CLI. Run the following command for this purpose: +The following command scaffolds a new Angular project named *my-angular-pivot-app*: -~~~json +~~~bash ng new my-angular-pivot-app ~~~ :::note -If you want to follow this guide, disable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering) when creating new Angular app! +Disable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering) when prompted by the Angular CLI — this guide assumes a client-rendered app. ::: -The command above installs all the necessary tools, so you don't need to run any additional commands. +The command installs all necessary tools. No additional commands are needed. -### Installation of dependencies +### Install dependencies -Go to the new created app directory: +Change into the new project directory: -~~~json +~~~bash cd my-angular-pivot-app ~~~ -Install dependencies and start the dev server. For this, use the [**yarn**](https://yarnpkg.com/) package manager: +Install dependencies and start the dev server with the [**yarn**](https://yarnpkg.com/) package manager: -~~~jsx +~~~bash yarn -yarn start // or yarn dev +yarn start # or: yarn dev ~~~ -The app should run on a localhost (for instance `http://localhost:3000`). +The app should run on a local port (for example, `http://localhost:3000`). -## Creating Pivot +## Create Pivot -Now you should get the DHTMLX Pivot source code. First of all, stop the app and proceed with installing the Pivot package. +Add the Pivot package to the project, then wrap Pivot in an Angular component. -### Step 1. Package installation +### Step 1. Install the package -Download the [**trial Pivot package**](/how-to-start/#installing-trial-pivot-via-npm-or-yarn) and follow steps mentioned in the README file. Note that trial Pivot is available 30 days only. +Download the [**trial Pivot package**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) and follow the steps in the README. The trial Pivot package is valid for 30 days. -### Step 2. Component creation +### Step 2. Create the component -Now you need to create an Angular component, to add Pivot into the application. Create the **pivot** folder in the ***src/app/*** directory, add a new file into it and name it ***pivot.component.ts***. Then complete the steps described below. +Create an Angular component that mounts Pivot. Add a *pivot* folder under *src/app/* and create *src/app/pivot/pivot.component.ts*. Then follow these steps: #### Import source files -Open the file and import Pivot source files. Note that: +Open *src/app/pivot/pivot.component.ts* and import the Pivot package. The import path depends on the package edition: -- if you use PRO version and install the Pivot package from a local folder, the imported path looks like this: +- **PRO version** (installed from a local folder): ~~~jsx import { Pivot } from 'dhx-pivot-package'; ~~~ -- if you use the trial version of Pivot, specify the following path: +- **Trial version**: ~~~jsx import { Pivot } from '@dhx/trial-pivot'; ~~~ -In this tutorial you can see how to configure the **trial** version of Pivot. +This tutorial uses the trial version of Pivot. + +#### Set up the container and mount Pivot -#### Set the container and initialize Pivot +To display Pivot on the page, define a container element in the component template, then initialize Pivot in the `ngOnInit` hook using the constructor. Destroy Pivot in the `ngOnDestroy` hook. -To display Pivot on the page, you need to set the container to render the component inside and initialize Pivot using the corresponding constructor: +The following code snippet defines a minimal Pivot Angular component: ~~~jsx {1,8,12-13,18-19} title="pivot.component.ts" import { Pivot } from '@dhx/trial-pivot'; @@ -87,13 +89,13 @@ import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation @Component({ encapsulation: ViewEncapsulation.None, - selector: "pivot", // a template name used in the "app.component.ts" file as - styleUrls: ["./pivot.component.css"], // include a css file + selector: "pivot", // template name used in the "app.component.ts" file as + styleUrls: ["./pivot.component.css"], // include a CSS file template: `
`, }) export class PivotComponent implements OnInit, OnDestroy { - // initialize container for Pivot + // container reference for Pivot @ViewChild('container', { static: true }) pivot_container!: ElementRef; private _table!: Pivot; @@ -104,20 +106,20 @@ export class PivotComponent implements OnInit, OnDestroy { } ngOnDestroy(): void { - this._table.destructor(); // destruct Pivot + this._table.destructor(); // destroy Pivot on unmount } } ~~~ -#### Adding styles +#### Add styles -To display Pivot correctly, you need to provide the corresponding styles. For this purpose, you can create the ***pivot.component.css*** file in the ***src/app/pivot/*** directory and specify important styles for Pivot and its container: +To render Pivot correctly, create *src/app/pivot/pivot.component.css* with styles for the page and the Pivot container: ~~~css title="pivot.component.css" /* import Pivot styles */ @import "@dhx/trial-pivot/dist/pivot.css"; -/* specify styles for initial page */ +/* styles for the initial page */ html, body { margin: 0; @@ -125,16 +127,16 @@ body { height: 100%; } -/* specify styles for the Pivot container */ +/* styles for the Pivot container */ .widget { width: 100%; height: 100%; } ~~~ -#### Loading data +#### Load data -To add data into Pivot, you need to provide a data set. You can create the ***data.ts*** file in the ***src/app/pivot/*** directory and add some data into it: +To feed data into Pivot, prepare a dataset. Create *src/app/pivot/data.ts* and export the data and field metadata: ~~~jsx title="data.ts" export function getData() { @@ -172,7 +174,7 @@ export function getData() { "state": "Colorado", "expenses": 45, "type": "Decaf" - }, // othe data items + }, // other data items ]; const fields: any = [ @@ -192,7 +194,7 @@ export function getData() { }; ~~~ -Then open the ***pivot.component.ts*** file. Import the file with data and specify the corresponding data properties to the configuration object of Pivot within the `ngOnInit()` method, as shown below. +Open *src/app/pivot/pivot.component.ts*, import `getData`, and apply the dataset in `ngOnInit()`: ~~~jsx {2,18,20-21} title="pivot.component.ts" import { Pivot } from '@dhx/trial-pivot'; @@ -212,7 +214,7 @@ export class PivotComponent implements OnInit, OnDestroy { private _table!: Pivot; ngOnInit() { - const { dataset, fields } = getData(); // initialize data properties + const { dataset, fields } = getData(); // unpack data and field metadata this._table = new Pivot(this.pivot_container.nativeElement, { fields, data: dataset, @@ -236,17 +238,18 @@ export class PivotComponent implements OnInit, OnDestroy { } ~~~ -Now the Pivot component is ready to use. When the element will be added to the page, it will initialize the Pivot with data. You can provide necessary configuration settings as well. Visit our [Pivot API docs](/api/overview/properties-overview/) to check the full list of available properties. +The component is now ready to use. On mount, Pivot renders with the supplied data. For the full list of configuration properties, see the [Pivot API docs](api/overview/properties-overview.md). -#### Handling events +#### Handle events -When a user makes some action in the Pivot, it invokes an event. You can use these events to detect the action and run the desired code for it. See the [full list of events](/api/overview/events-overview/). +User actions in Pivot fire events that you can subscribe to. For the full list of events, see [Events overview](api/overview/events-overview.md). -Open the ***pivot.component.ts*** file and complete the `ngOnInit()` method as in: +The following code snippet extends `ngOnInit` with an `open-filter` event listener that logs the field ID when a user opens a filter: ~~~jsx {18-20} title="pivot.component.ts" // ... ngOnInit() { + const { dataset, fields } = getData(); this._table = new Pivot(this.pivot_container.nativeElement, { fields, data: dataset, @@ -263,7 +266,7 @@ ngOnInit() { }); this._table.api.on("open-filter", (ev) => { - console.log("The field id for which filter is activated:", ev.id); + console.log("The field id for which the filter is activated:", ev.id); }); } @@ -272,23 +275,23 @@ ngOnDestroy(): void { } ~~~ -### Step 3. Adding Pivot into the app +### Step 3. Add Pivot to the app -To add the ***PivotComponent*** into the app, open the ***src/app/app.component.ts*** file and replace the default code with the following one: +To embed `PivotComponent` in the app, open *src/app/app.component.ts* and replace the default code with the following: ~~~jsx {5} title="app.component.ts" import { Component } from "@angular/core"; @Component({ selector: "app-root", - template: `` // a template created in the "pivot.component.ts" file + template: `` // template created in the "pivot.component.ts" file }) export class AppComponent { name = ""; } ~~~ -Then create the ***app.module.ts*** file in the ***src/app/*** directory and specify the *PivotComponent* as shown below: +Then create *src/app/app.module.ts* and register `PivotComponent`: ~~~jsx {4-5,8} title="app.module.ts" import { NgModule } from "@angular/core"; @@ -305,7 +308,7 @@ import { PivotComponent } from "./pivot/pivot.component"; export class AppModule {} ~~~ -The last step is to open the ***src/main.ts*** file and replace the existing code with the following one: +Finally, open *src/main.ts* and replace its contents with the following bootstrap code: ~~~jsx title="main.ts" import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; @@ -315,8 +318,8 @@ platformBrowserDynamic() .catch((err) => console.error(err)); ~~~ -After that, you can start the app to see Pivot loaded with data on a page. +Start the app to see Pivot render the data on the page. ![Pivot initialization](../assets/trial_pivot.png) -Now you know how to integrate DHTMLX Pivot with Angular. You can customize the code according to your specific requirements. The final example you can find on [**GitHub**](https://github.com/DHTMLX/angular-pivot-demo). +Pivot is now integrated with Angular. Customize the configuration to suit the project requirements. For the final example, see [**angular-pivot-demo on GitHub**](https://github.com/DHTMLX/angular-pivot-demo). diff --git a/docs/guides/integration-with-react.md b/docs/guides/integration-with-react.md index cfc984d..e8c4f6a 100644 --- a/docs/guides/integration-with-react.md +++ b/docs/guides/integration-with-react.md @@ -7,86 +7,90 @@ description: You can learn about the integration with React in the documentation # Integration with React :::tip -You should be familiar with the basic concepts and patterns of [**React**](https://react.dev) before reading this documentation. To refresh your knowledge, please refer to the [**React documentation**](https://react.dev/learn). +Familiarity with the basic concepts and patterns of [**React**](https://react.dev) is assumed. To refresh, see the [**React documentation**](https://react.dev/learn). ::: -DHTMLX Pivot is compatible with **React**. We have prepared code examples on how to use DHTMLX Pivot with **React**. For more information, refer to the corresponding [**Example on GitHub**](https://github.com/DHTMLX/react-pivot-demo). +DHTMLX Pivot integrates with **React** as a regular component. For a full working setup, see the [**React Pivot demo on GitHub**](https://github.com/DHTMLX/react-pivot-demo). -## Creating a project +## Create a project :::info -Before you start to create a new project, install [**Vite**](https://vite.dev/) (optional) and [**Node.js**](https://nodejs.org/en/). +Install [**Node.js**](https://nodejs.org/en/) before you start. [**Vite**](https://vite.dev/) is optional. ::: -You can create a basic **React** project or use **React with Vite**. Let's name the project as **my-react-pivot-app**: +Create a basic **React** project (or a Vite-based one) named *my-react-pivot-app*. -~~~json +The following command bootstraps a Create React App project: + +~~~bash npx create-react-app my-react-pivot-app ~~~ -### Installation of dependencies +### Install dependencies -Go to the new created app directory: +Change into the new project directory: -~~~json +~~~bash cd my-react-pivot-app ~~~ -Install dependencies and start the dev server. For this, use a package manager: +Install dependencies and start the dev server with your package manager: -- if you use [**yarn**](https://yarnpkg.com/), run the following commands: +- with [**yarn**](https://yarnpkg.com/): -~~~jsx +~~~bash yarn -yarn start // or yarn dev +yarn start # or: yarn dev ~~~ -- if you use [**npm**](https://www.npmjs.com/), run the following commands: +- with [**npm**](https://www.npmjs.com/): -~~~json +~~~bash npm install npm run dev ~~~ -The app should run on a localhost (for instance `http://localhost:3000`). +The app should run on a local port (for example, `http://localhost:3000`). -## Creating Pivot +## Create Pivot -Now you should get the DHTMLX Pivot source code. First of all, stop the app and proceed with installing the Pivot package. +Add the Pivot package to the project, then wrap Pivot in a React component. -### Step 1. Package installation +### Step 1. Install the package -Download the [**trial Pivot package**](/how-to-start/#installing-trial-pivot-via-npm-or-yarn) and follow steps mentioned in the README file. Note that trial Pivot is available 30 days only. +Download the [**trial Pivot package**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) and follow the steps in the README. The trial Pivot package is valid for 30 days. -### Step 2. Component creation +### Step 2. Create the component -Now you need to create a React component, to add a Pivot into the application. Create a new file in the ***src/*** directory and name it ***Pivot.jsx***. +Create a React component that mounts Pivot. Add a new file *src/Pivot.jsx*. #### Import source files -Open the ***Pivot.jsx*** file and import Pivot source files. Note that: +Open *src/Pivot.jsx* and import the Pivot source files. The import paths depend on the package edition: -- if you use PRO version and install the Pivot package from a local folder, the import paths look like this: +- **PRO version** (installed from a local folder): ~~~jsx title="Pivot.jsx" import { Pivot } from 'dhx-pivot-package'; import 'dhx-pivot-package/dist/pivot.css'; ~~~ -Note that depending on the used package, the source files can be minified. In this case make sure that you are importing the CSS file as ***pivot.min.css***. +If the package ships minified assets, import *pivot.min.css* instead of *pivot.css*. -- if you use the trial version of Pivot, specify the following paths: +- **Trial version**: ~~~jsx title="Pivot.jsx" import { Pivot } from '@dhx/trial-pivot'; import "@dhx/trial-pivot/dist/pivot.css"; ~~~ -In this tutorial you can see how to configure the **trial** version of Pivot. +This tutorial uses the trial version of Pivot. + +#### Set up the container and mount Pivot -#### Setting the container and adding Pivot +To display Pivot on the page, create a container `div`, then initialize Pivot in a `useEffect` hook using the constructor. -To display Pivot on the page, you need to create the container for Pivot, and initialize this component using the corresponding constructor: +The following code snippet defines a minimal Pivot React component: ~~~jsx {2,6,9-10} title="Pivot.jsx" import { useEffect, useRef } from "react"; @@ -94,14 +98,14 @@ import { Pivot } from "@dhx/trial-pivot"; import "@dhx/trial-pivot/dist/pivot.css"; // include Pivot styles export default function PivotComponent(props) { - let container = useRef(); // initialize container for Pivot + let container = useRef(); // container ref for Pivot useEffect(() => { // initialize the Pivot component const table = new Pivot(container.current, {}); return () => { - table.destructor(); // destruct Pivot + table.destructor(); // destroy Pivot on unmount }; }, []); @@ -109,12 +113,12 @@ export default function PivotComponent(props) { } ~~~ -#### Adding styles +#### Add styles -To display Pivot correctly, you need to specify important styles for Pivot and its container in the main css file of the project: +To render Pivot correctly, add the following styles to the project's main CSS file: ~~~css title="index.css" -/* specify styles for initial page */ +/* styles for the initial page */ html, body, #root { @@ -123,16 +127,16 @@ body, margin: 0; } -/* specify styles for the Pivot container */ +/* styles for the Pivot container */ .widget { height: 100%; width: 100%; } ~~~ -#### Loading data +#### Load data -To add data into the Pivot, you need to provide a data set. You can create the ***data.js*** file in the ***src/*** directory and add some data into it: +To feed data into Pivot, prepare a dataset. Create *src/data.js* and export the data and field metadata: ~~~jsx title="data.js" export function getData() { @@ -170,7 +174,7 @@ export function getData() { "state": "Colorado", "expenses": 45, "type": "Decaf" - }, // othe data items + }, // other data items ]; const fields = [ @@ -190,7 +194,7 @@ export function getData() { }; ~~~ -Then open the ***App.js*** file and import data. After this you can pass data into the new created `` components as **props**: +Open *src/App.js*, import the data, and pass it to the `` component as props: ~~~jsx {2,5-6} title="App.js" import Pivot from "./Pivot"; @@ -204,14 +208,14 @@ function App() { export default App; ~~~ -Go to the ***Pivot.jsx*** file and apply the passed **props** to the Pivot configuration object: +Open *src/Pivot.jsx*, destructure the props, and apply them to the Pivot configuration object: ~~~jsx {5,10-11} title="Pivot.jsx" import { useEffect, useRef } from "react"; import { Pivot } from "@dhx/trial-pivot"; import "@dhx/trial-pivot/dist/pivot.css"; -export default function PivotComponent(props) { +export default function PivotComponent({ fields, dataset }) { let container = useRef(); useEffect(() => { @@ -240,13 +244,13 @@ export default function PivotComponent(props) { } ~~~ -Now the Pivot component is ready to use. When the element will be added to the page, it will initialize the Pivot with data. You can provide necessary configuration settings as well. Visit our [Pivot API docs](/api/overview/properties-overview/) to check the full list of available properties. +The component is now ready to use. On mount, Pivot renders with the supplied data. For the full list of configuration properties, see the [Pivot API docs](api/overview/properties-overview.md). -#### Handling events +#### Handle events -When a user makes some action in the Pivot, it invokes an event. You can use these events to detect the action and run the desired code for it. See the [full list of events](/api/overview/events-overview/). +User actions in Pivot fire events that you can subscribe to. For the full list of events, see [Events overview](api/overview/events-overview.md). -Open ***Pivot.jsx*** and complete the `useEffect()` method in the following way: +The following code snippet extends `useEffect` with an `open-filter` event listener that logs the field ID when a user opens a filter: ~~~jsx {19-21} title="Pivot.jsx" // ... @@ -268,7 +272,7 @@ useEffect(() => { }); table.api.on("open-filter", (ev) => { - console.log("The field id for which filter is activated:", ev.id); + console.log("The field id for which the filter is activated:", ev.id); }); return () => { @@ -278,8 +282,8 @@ useEffect(() => { // ... ~~~ -After that, you can start the app to see Pivot loaded with data on a page. +Start the app to see Pivot render the data on the page. ![Pivot initialization](../assets/trial_pivot.png) -Now you know how to integrate DHTMLX Pivot with React. You can customize the code according to your specific requirements. The final example you can find on [**GitHub**](https://github.com/DHTMLX/react-pivot-demo). +Pivot is now integrated with React. Customize the configuration to suit the project requirements. For the final example, see [**react-pivot-demo on GitHub**](https://github.com/DHTMLX/react-pivot-demo). diff --git a/docs/guides/integration-with-svelte.md b/docs/guides/integration-with-svelte.md index d0510d2..f6880f5 100644 --- a/docs/guides/integration-with-svelte.md +++ b/docs/guides/integration-with-svelte.md @@ -7,68 +7,68 @@ description: You can learn about the integration with Svelte in the documentatio # Integration with Svelte :::tip -You should be familiar with the basic concepts and patterns of **Svelte** before reading this documentation. To refresh your knowledge, please refer to the [**Svelte documentation**](https://svelte.dev/). +Familiarity with the basic concepts and patterns of **Svelte** is assumed. To refresh, see the [**Svelte documentation**](https://svelte.dev/). ::: -DHTMLX Pivot is compatible with **Svelte**. We have prepared code examples on how to use DHTMLX Pivot with **Svelte**. For more information, refer to the corresponding [**Example on GitHub**](https://github.com/DHTMLX/svelte-pivot-demo). +DHTMLX Pivot integrates with **Svelte** as a regular component. For a full working setup, see the [**Svelte Pivot demo on GitHub**](https://github.com/DHTMLX/svelte-pivot-demo). -## Creating a project +## Create a project :::info -Before you start to create a new project, install [**Vite**](https://vite.dev/) (optional) and [**Node.js**](https://nodejs.org/en/). +Install [**Node.js**](https://nodejs.org/en/) before you start. [**Vite**](https://vite.dev/) is optional. ::: -To create a **Svelte** JS project, run the following command: +The following command runs the Vite project scaffolding tool and lets you pick a Svelte template: -~~~json +~~~bash npm create vite@latest ~~~ -Let's name the project as **my-svelte-pivot-app**. +Name the project *my-svelte-pivot-app*. -### Installation of dependencies +### Install dependencies -Go to the app directory: +Change into the new project directory: -~~~json +~~~bash cd my-svelte-pivot-app ~~~ -Install dependencies and start the dev server. For this, use a package manager: +Install dependencies and start the dev server with your package manager: -- if you use [**yarn**](https://yarnpkg.com/), run the following commands: +- with [**yarn**](https://yarnpkg.com/): -~~~jsx +~~~bash yarn -yarn start // or yarn dev +yarn start # or: yarn dev ~~~ -- if you use [**npm**](https://www.npmjs.com/), run the following commands: +- with [**npm**](https://www.npmjs.com/): -~~~json +~~~bash npm install npm run dev ~~~ -The app should run on a localhost (for instance `http://localhost:3000`). +The app should run on a local port (for example, `http://localhost:3000`). -## Creating Pivot +## Create Pivot -Now you should get the DHTMLX Pivot source code. First of all, stop the app and proceed with installing the Pivot package. +Add the Pivot package to the project, then wrap Pivot in a Svelte component. -### Step 1. Package installation +### Step 1. Install the package -Download the [**trial Pivot package**](/how-to-start/#installing-trial-pivot-via-npm-or-yarn) and follow steps mentioned in the README file. Note that trial Pivot is available 30 days only. +Download the [**trial Pivot package**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) and follow the steps in the README. The trial Pivot package is valid for 30 days. -### Step 2. Component creation +### Step 2. Create the component -Now you need to create a Svelte component, to add Pivot into the application. Let's create a new file in the ***src/*** directory and name it ***Pivot.svelte***. +Create a Svelte component that mounts Pivot. Add a new file *src/Pivot.svelte*. #### Import source files -Open the ***Pivot.svelte*** file and import Pivot source files. Note that: +Open *src/Pivot.svelte* and import the Pivot source files. The import paths depend on the package edition: -- if you use PRO version and install the Pivot package from a local folder, the import paths look like this: +- **PRO version** (installed from a local folder): ~~~html title="Pivot.svelte" ~~~ -Note that depending on the used package, the source files can be minified. In this case make sure that you are importing the CSS file as ***pivot.min.css***. +If the package ships minified assets, import *pivot.min.css* instead of *pivot.css*. -- if you use the trial version of Pivot, specify the following paths: +- **Trial version**: ~~~html title="Pivot.svelte" ~~~ -In this tutorial you can see how to configure the **trial** version of Pivot. +This tutorial uses the trial version of Pivot. -#### Setting the container and adding Pivot +#### Set up the container and mount Pivot -To display Pivot on the page, you need to create the container for Pivot, and initialize this component using the corresponding constructor: +To display Pivot on the page, add a container `div`, then initialize Pivot in the `onMount` lifecycle hook using the constructor. Destroy Pivot in the `onDestroy` hook. + +The following code snippet defines a minimal Pivot Svelte component: ~~~html {3,6,10-11,19} title="Pivot.svelte"
~~~ -#### Adding styles +#### Add styles -To display Pivot correctly, you need to specify important styles for Pivot and its container in the main css file of the project: +To render Pivot correctly, add the following styles to the project's main CSS file: ~~~css title="main.css" -/* specify styles for initial page */ +/* styles for the initial page */ html, body, -#app { /* make sure that you use the #app root container */ +#app { /* use the #app root container */ height: 100%; padding: 0; margin: 0; } -/* specify styles for the Pivot container */ +/* styles for the Pivot container */ .widget { height: 100%; width: 100%; } ~~~ -#### Loading data +#### Load data -To add data into the Pivot, we need to provide a data set. You can create the ***data.js*** file in the ***src/*** directory and add some data into it: +To feed data into Pivot, prepare a dataset. Create *src/data.js* and export the data and field metadata: ~~~jsx title="data.js" export function getData() { @@ -177,7 +179,7 @@ export function getData() { "state": "Colorado", "expenses": 45, "type": "Decaf" - }, // othe data items + }, // other data items ]; const fields = [ @@ -197,20 +199,20 @@ export function getData() { }; ~~~ -Then open the ***App.svelte*** file, import data, and pass it into the new created `` components as **props**: +Open *src/App.svelte*, import the data, and pass it to the new `` component as props: ~~~html {3,5,8} title="App.svelte" ~~~ -Go to the ***Pivot.svelte*** file and apply the passed **props** to the Pivot configuration object: +Open *src/Pivot.svelte*, declare the incoming props with `export let`, and apply them to the Pivot configuration object: ~~~html {6-7,14-15} title="Pivot.svelte" ~~~ -Note that depending on the used package, the source files can be minified. In this case make sure that you are importing the CSS file as ***pivot.min.css***. +If the package ships minified assets, import *pivot.min.css* instead of *pivot.css*. -- if you use the trial version of Pivot, specify the following paths: +- **Trial version**: ~~~html title="Pivot.vue" ~~~ -In this tutorial you can see how to configure the **trial** version of Pivot. +This tutorial uses the trial version of Pivot. + +#### Set up the container and mount Pivot -#### Setting the container and adding Pivot +To display Pivot on the page, add a container `div`, then initialize Pivot in the `mounted` hook using the constructor. Destroy Pivot in the `unmounted` hook. -To display Pivot on the page, you need to create the container for Pivot, and initialize this component using the corresponding constructor: +The following code snippet defines a minimal Pivot Vue component: ~~~html {2,7-8,18} title="Pivot.vue" @@ -118,30 +120,30 @@ export default { ~~~ -#### Adding styles +#### Add styles -To display Pivot correctly, you need to specify important styles for Pivot and its container in the main css file of the project: +To render Pivot correctly, add the following styles to the project's main CSS file: ~~~css title="style.css" -/* specify styles for initial page */ +/* styles for the initial page */ html, body, -#app { /* make sure that you use the #app root container */ +#app { /* use the #app root container */ height: 100%; padding: 0; margin: 0; } -/* specify styles for the Pivot container */ +/* styles for the Pivot container */ .widget { width: 100%; height: 100%; } ~~~ -#### Loading data +#### Load data -To add data into the Pivot, you need to provide a data set. You can create the ***data.js*** file in the ***src/*** directory and add some data into it: +To feed data into Pivot, prepare a dataset. Create *src/data.js* and export the data and field metadata: ~~~jsx title="data.js" export function getData() { @@ -179,7 +181,7 @@ export function getData() { "state": "Colorado", "expenses": 45, "type": "Decaf" - }, // othe data items + }, // other data items ]; const fields = [ @@ -199,7 +201,7 @@ export function getData() { }; ~~~ -Then open the ***App.vue*** file, import data, and initialize it via the inner `data()` method. After this you can pass data into the new created `` component as **props**: +Open *src/App.vue*, import the data, and expose it through the `data()` option. Then pass the values to the new `` component as props: ~~~html {3,7-13,18} title="App.vue" @@ -136,38 +134,44 @@ Second, add the path to the source data file: ~~~ -Create Pivot and load data: +The following code snippet creates Pivot and loads data from the prepared file: ~~~jsx const { data, config, fields } = getData(); const table = new pivot.Pivot("#root", { data, config, fields }); ~~~ -To get server data, you can send the request for data using the native **fetch** method (or any other way): +## Load data from a server + +To load data from a server endpoint, send a request with the native `fetch` method (or any equivalent), then pass the response to [`setConfig`](api/methods/setconfig-method.md), which updates the Pivot configuration and preserves previously set options. + +The following code snippet initializes Pivot with empty data, fetches data and fields from a server, then applies them with `setConfig`: ~~~jsx -const table = new pivot.Pivot("#root", {fields:[], data: []}); +const table = new pivot.Pivot("#root", { fields: [], data: [] }); const server = "https://some-backend-url"; Promise.all([ fetch(server + "/data").then((res) => res.json()), fetch(server + "/fields").then((res) => res.json()) ]).then(([data, fields]) => { - table.setConfig({data, fields}); + table.setConfig({ data, fields }); }); ~~~ -## Loading CSV data +Refer to the following topic for additional information: [Working with server](/guides/working-with-server) + +## Load CSV data -You can load CSV data and convert it to JSON and then continue working with this data in the Pivot table. +Pivot accepts CSV data after you convert it to JSON with an external JS parsing library. The converted data behaves the same as native JSON. -To convert data, you should use an external parsing library for JS to convert data from CSV to JSON. +The example below uses the external [PapaParse](https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js) library to load and convert data on a button click. The `convert()` helper takes the following parameters: -In the example below we apply the external [PapaParse](https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js) library and enable loading and converting data on a button click. In this example we use the `convert()` function which takes the following parameters: +- `data` — a string with CSV data +- `headers` — an array of CSV field names +- `meta` — an object mapping field names to data types -- `data` - a string with CSV data -- `headers` - an array with the names of fields for CSV data -- `meta` - an object where keys are the names of fields and values are the data types +The following code snippet creates Pivot, defines the `convert()` helper, and applies parsed CSV data through [`setConfig`](api/methods/setconfig-method.md) on a button click: ~~~jsx const table = new pivot.Pivot("#root", { @@ -238,7 +242,7 @@ function fromCSV() { "when" ]; - // date fields must be explicitly marked for proper conversion + // mark date fields explicitly for proper conversion const meta = { when: "date" }; const dataURL = "https://some-backend-url"; @@ -263,13 +267,13 @@ document.body.appendChild(importButton); ## Example -In this snippet you can see how to load JSON and CSV data: +The snippet below loads JSON and CSV data: -**Related samples:** +**Related samples**: - [Pivot 2. Date format](https://snippet.dhtmlx.com/shn1l794) - [Pivot 2. Different datasets](https://snippet.dhtmlx.com/6xtqge4i) - [Pivot 2. Large dataset](https://snippet.dhtmlx.com/e6qwqrys) -**Related articles**: [Date formatting](/guides/localization#date-formatting) \ No newline at end of file +**Related articles**: [Date formatting](guides/localization.md#date-formatting) diff --git a/docs/guides/localization.md b/docs/guides/localization.md index 2c3be82..81f60af 100644 --- a/docs/guides/localization.md +++ b/docs/guides/localization.md @@ -6,15 +6,15 @@ description: You can learn about the localization in the documentation of the DH # Localization -You can localize all labels in the interface of JavaScript Pivot. For this purpose you need to create a new locale or modify a built-in one and apply it to Pivot. +Pivot lets you localize every label in the interface. Create a new locale or modify a built-in one, then apply the locale to Pivot via the [`locale`](api/config/locale-property.md) property or the [`setLocale`](api/methods/setlocale-method.md) method. ## Default locale -The **English** locale is applied by default: +Pivot applies the English locale by default. The following code snippet shows the structure of the built-in `en` locale: ~~~jsx const en = { - //pivot + // pivot pivot: { sum: "Sum", min: "Min", @@ -49,7 +49,7 @@ const en = { "Hide settings": "Hide settings" }, - //query + // query query: { "Add filter": "Add filter", "Add Filter": "Add Filter", @@ -84,7 +84,7 @@ const en = { "not between": "not between" }, - //calendar + // calendar calendar: { monthFull: [ "January", @@ -138,65 +138,73 @@ const en = { clockFormat: 24, }, - //core + // core core: { - ok:"OK", - cancel:"Cancel", + ok: "OK", + cancel: "Cancel", select: "Select", "No data": "No data" }, - //formats + // formats formats: { dateFormat: "%d.%m.%Y", timeFormat: "%H:%i" - } + }, lang: "en-US", }; ~~~ -## Applying locales +## Apply a locale -You can access built-in locales via the pivot object. Pivot provides three built-in locales: en, de, cn. +Pivot exposes three built-in locales through the `pivot.locales` object: `en`, `de`, and `cn`. Pass a built-in locale to the [`locale`](api/config/locale-property.md) property during initialization. -Example: +The following code snippet initializes Pivot with the German locale: ~~~jsx -new pivot.Pivot({ +new pivot.Pivot("#root", { // other properties locale: pivot.locales.de, }); ~~~ -To apply a custom locale, you need to: +To apply a custom locale: + +- create a locale object (or modify a built-in one) and provide translations for all text labels (in any language) +- apply the locale to Pivot via the [`locale`](api/config/locale-property.md) property or the [`setLocale`](api/methods/setlocale-method.md) method -- create a custom locale object (or modify the default one) and provide translations for all text labels (it can be any language you need) -- apply the new locale to Pivot via its [`locale`](/api/config/locale-property) property or use the [`setLocale()`](/api/methods/setlocale-method) method +The following code snippet creates Pivot, then applies a custom Korean locale at runtime with `setLocale`: ~~~jsx // create Pivot const widget = new pivot.Pivot("#root", { - data, -//other configuration properties + data, + // other configuration properties }); -const ko = {...} //object with locale +const ko = { /* object with locale */ }; widget.setLocale(ko); ~~~ -## Date formatting +:::tip +Call [`setLocale`](api/methods/setlocale-method.md) without arguments (or with `null`) to reset Pivot to the default English locale. +::: -Pivot accepts a date as a Date object (make sure to parse a date to a Date object). By default, the `dateFormat` of the current locale is applied. To redefine the format for all date fields in Pivot, change the value of the `dateFormat` parameter in the `formats` object of the [`locale`](/api/config/locale-property). The default format is "%d.%m.%Y". +## Format dates {#date-formatting} -Example: +Pivot accepts dates as `Date` objects. Parse string values to `Date` before passing data to Pivot. The default `dateFormat` is `"%d.%m.%Y"`, taken from the current locale. + +To change the format for all date fields, set a new value for `dateFormat` in the `formats` object of the [`locale`](api/config/locale-property.md) property. + +The following code snippet parses string dates into `Date` objects, then initializes Pivot with a custom `dateFormat` and updates the format at runtime via `setConfig`: ~~~jsx {17} function setFormat(value) { table.setConfig({ locale: { formats: { dateFormat: value } } }); } -// date string to Date +// convert date strings to Date objects const dateFields = fields.filter((f) => f.type == "date"); if (dateFields.length) { dataset.forEach((item) => { @@ -232,11 +240,11 @@ const table = new pivot.Pivot("#root", { }); ~~~ -In case you need to set a custom format to a specific field, use the `format` parameter of the [`fields`](/api/config/fields-property) property. Refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields). +To set a custom format for a specific field, use the `format` parameter of the [`fields`](api/config/fields-property.md) property. See [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields). -## Date and time format specification +## Date and time format characters -Pivot uses the following characters for setting the date and time format: +Pivot uses the following characters to define the date and time format: | Character | Definition |Example | | :-------- | :------------------------------------------------ |:------------------------| @@ -262,22 +270,24 @@ Pivot uses the following characters for setting the date and time format: | %A | AM or PM | AM (for time from midnight until noon) and PM (for time from noon until midnight)| | %c | displays date and time in the ISO 8601 date format| 2024-10-04T05:04:09 | +To present September 20, 2024 at 16:47:08.128 as *2024-09-20 16:47:08.128*, use the format `"%Y-%m-%d %H:%i:%s.%S"`. + +## Format numbers {#number-formatting} -To present the 20th of June, 2024 with the exact time as *2024-09-20 16:47:08.128*, specify "%Y-%m-%d-%H:%i:%s.%u". +Pivot localizes all `number` fields based on the `lang` value of the current locale. The widget uses the [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) specification. The default settings limit fraction digits to 3 and apply group separation to the integer part. -## Number formatting +To skip formatting for a specific numeric field or to set a custom format, use the `format` parameter of the [`fields`](api/config/fields-property.md) property. Set `format` to `false` to disable formatting, or to an object with format settings (see [Applying formats to fields](guides/working-with-data.md#applying-formats-to-fields)). -By default, all fields with the number type are localized according to the locale (the value in the `lang` field of the locale). Pivot uses [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) specification. By default the fraction digits are limited to 3 and group separation is applied for the integer part. -In case you do not need to format specific fields with numeric values or need to set a custom format, use the the `format` parameter of the [`fields`](/api/config/fields-property) property. It can be either *false* to cancel formatting or an object with format settings (refer to [Applying formats to fields](/guides/working-with-data/#applying-formats-to-fields)). +The following code snippet disables number formatting for the `year` field: ~~~jsx const fields = [ - { id: "year", label: "Year", type: "number", format: false}, + { id: "year", label: "Year", type: "number", format: false }, ]; ~~~ ## Example -In this snippet you can see how to switch between several locales: +The snippet below switches between several locales: diff --git a/docs/guides/stylization.md b/docs/guides/stylization.md index 3b2967c..bd88622 100644 --- a/docs/guides/stylization.md +++ b/docs/guides/stylization.md @@ -6,8 +6,12 @@ description: You can learn about the styling in the documentation of the DHTMLX # Styling +Pivot ships with a default theme and exposes CSS variables and utility classes for customization. Override the variables on the widget container (or any ancestor) to change colors, borders, and other visual properties. + ## Default style +The default Pivot theme is **Material**. The following CSS snippet shows the variables that the Material theme sets on the widget container: + ~~~css .wx-material-theme { --wx-theme-name: material; @@ -21,22 +25,21 @@ description: You can learn about the styling in the documentation of the DHTMLX ~~~ :::tip Note -Next versions of Pivot can bring some changes for the variables and their names. Please, do not forget to check the names after updating to the newer versions and modify them in your code to avoid problems with display of the component. +Future versions of Pivot may rename CSS variables. Check the variable names after upgrading and update them in your code to avoid display issues. ::: ## Built-in theme -The widget provides one built-in theme which is the **Material** theme. +Pivot provides one built-in theme: **Material**. Apply the theme either by adding the theme class to the widget container or by including the prebuilt skin stylesheet on the page. -You can apply the theme via adding the corresponding *CSS* classes to the widget container: +The following code snippet applies the Material theme by adding the `wx-material-theme` class to the widget container: -- **Material theme** ~~~html {}
~~~ -or just include the theme on the page from the skins folder: +The following code snippet includes the Material skin stylesheet directly: ~~~html {} @@ -44,7 +47,9 @@ or just include the theme on the page from the skins folder: ## Customize built-in theme -The example below demonstrates how to customize the **Material** theme that is applied to the Pivot table: +Override the Material theme variables on the `.wx-material-theme` selector to change colors, borders, and other visual properties. + +The example below overrides Material theme variables to render Pivot in a dark color scheme: ~~~html @@ -70,9 +75,9 @@ The example below demonstrates how to customize the **Material** theme that is a ## Custom style -You can change the appearance of Pivot by applying the corresponding CSS variables. +Change the appearance of Pivot by overriding the CSS variables on a custom class applied to the widget container. -The example below shows how to apply a custom style to Pivot: +The example below applies a custom style to Pivot via the `.demo` class: ~~~html
@@ -91,20 +96,23 @@ The example below shows how to apply a custom style to Pivot: ## Scroll style -You can also apply a custom style to the scroll bar of Pivot. For this, you can use the `.wx-styled-scroll` CSS class. Before using it, check compatibility with the modern browsers [here](https://caniuse.com/css-scrollbar). +Apply a custom style to the Pivot scroll bar with the `.wx-styled-scroll` CSS class. Check browser compatibility before use: [caniuse: CSS Scrollbar](https://caniuse.com/css-scrollbar). + +The following code snippet enables the styled scroll bar on the widget container: ~~~html {} title="index.html" - +
~~~ ## Cell style -To apply a CSS class to the table body or footer cells, use the `cellStyle` parameter of the [`tableShape`](/api/config/tableshape-property) property. The style of the header cells can be customized via the `cellStyle` parameter of the [`headerShape`](/api/config/tableshape-property) property. In both cases the `cellStyle` function returns a string, which can be used as a CSS class name to apply specific styles to a cell. +To style body or footer cells, use the `cellStyle` parameter of the [`tableShape`](api/config/tableshape-property.md) property. To style header cells, use the `cellStyle` parameter of the [`headerShape`](api/config/headershape-property.md) property. In both cases, the `cellStyle` function returns a CSS class name that Pivot applies to the cell. + +The example below applies styles to body and header cells: -In the example below the styles of cells in the table body and headers are customized in the following way: -- for the table body cells, styles are applied dynamically based on cell values (e.g., "Down", "Up", "Idle") in the "status" field and on total values (greater than 40 or less than 5) -- the style of header cells is determined by the value in the "streaming" field, with specific styles applied for "no" or other values (the CSS class "status-down" is applied for the "no" value and "status-up" is applied for the not "no" value) +- body cells receive a class based on cell values (e.g., `"Down"`, `"Up"`, `"Idle"` in the `status` field) and on total values (greater than 40 or less than 5) +- header cells receive a class based on the value of the `streaming` field — `status-down` for `"no"` and `status-up` for any other value ~~~jsx const widget = new pivot.Pivot("#pivot", { @@ -155,14 +163,15 @@ const widget = new pivot.Pivot("#pivot", { }); ~~~ -## Marking values in cells +## Mark values in cells + +Use the `marks` parameter of the [`tableShape`](api/config/tableshape-property.md) property to apply a CSS class to cells that meet a condition. Each entry in `marks` pairs a CSS class name (the key) with a rule (the value). -The widget API allows marking required values in cells. You can do it by applying the `marks` parameter of the [`tableShape`](/api/config/tableshape-property) property. You need to do the following: -- create a CSS class to be applied to the marked cell -- add the CSS class name as the parameter of the `marks` object -- set its value which can be a custom function or one of the predefined strings ("max", "min"). The function should return boolean for the checked value; if **true** is returned, the css class is assigned to the cell. +The rule is either a predefined string (`"max"` or `"min"`) or a custom function `(value, columnData, rowData) => boolean`. When the function returns `true`, Pivot adds the CSS class to the cell. -In the example below, cells with min and max values are marked, and custom function is used to mark cells with values that are non-integer and greater than 2. +Create the CSS classes in your stylesheet before applying `marks`. + +The example below highlights cells with the minimum and maximum values, and uses a custom function to mark non-integer values greater than 2: ~~~jsx {18-26} const table = new pivot.Pivot("#root", { @@ -194,6 +203,8 @@ const table = new pivot.Pivot("#root", { }); ~~~ +The following code snippet defines the CSS classes referenced by the `marks` object above: + ~~~html title="index.html" ~~~ -It's also possible to customize the style of total columns via the ` .wx-total` CSS class: +To style total columns, override the `.wx-total` CSS class. + +The following code snippet styles total cells with a light background and a heavier font weight: ~~~html +~~~ + +## Benutzerdefinierter Style {#custom-style} + +Ändern Sie das Erscheinungsbild von Pivot, indem Sie die CSS-Variablen mit einer benutzerdefinierten Klasse am Widget-Container überschreiben. + +Das folgende Beispiel wendet über die Klasse `.demo` einen benutzerdefinierten Style auf Pivot an: + +~~~html +
+ +~~~ + +## Scroll-Style {#scroll-style} + +Wenden Sie mit der CSS-Klasse `.wx-styled-scroll` einen benutzerdefinierten Style auf die Pivot-Scrollleiste an. Prüfen Sie die Browser-Kompatibilität vor der Verwendung: [caniuse: CSS Scrollbar](https://caniuse.com/css-scrollbar). + +Der folgende Code-Ausschnitt aktiviert die gestaltete Scrollleiste am Widget-Container: + +~~~html {} title="index.html" + +
+~~~ + +## Zellen-Style {#cell-style} + +Um Body- oder Footer-Zellen zu gestalten, verwenden Sie den Parameter `cellStyle` der Eigenschaft [`tableShape`](api/config/tableshape-property.md). Um Header-Zellen zu gestalten, verwenden Sie den Parameter `cellStyle` der Eigenschaft [`headerShape`](api/config/headershape-property.md). In beiden Fällen gibt die Funktion `cellStyle` einen CSS-Klassenamen zurück, den Pivot auf die Zelle anwendet. + +Das folgende Beispiel wendet Styles auf Body- und Header-Zellen an: + +- Body-Zellen erhalten eine Klasse basierend auf Zellwerten (z. B. `"Down"`, `"Up"`, `"Idle"` im Feld `status`) und auf Gesamtwerten (größer als 40 oder kleiner als 5) +- Header-Zellen erhalten eine Klasse basierend auf dem Wert des Feldes `streaming` — `status-down` für `"no"` und `status-up` für jeden anderen Wert + +~~~jsx +const widget = new pivot.Pivot("#pivot", { + tableShape: { + totalColumn: true, + totalRow:true, + cellStyle: (field, value, area, method, isTotal) => { + if (field === "status" && area === "rows" && value) { + if (value === "Down") { + return "status-down"; + } else if (value === "Up") { + return "status-up"; + } else if (value === "Idle") { + return "status-idle"; + } + } + if(isTotal ==="column" && area == "values"){ + if(value > 40) + return "status-up"; + else if (value < 5) + return "status-down"; + } + } + }, + headerShape:{ + cellStyle:(field, value, area, method, isTotal) => { + if(field == "streaming") + return value ==="no"?"status-down":"status-up"; + } + }, + fields, + data: dataset, + config: { + rows: [ + "protocol", + "status", + ], + columns: [ + "streaming" + ], + values: [ + { + field: "id", + method: "count" + } + ] + } +}); +~~~ + +## Werte in Zellen markieren {#mark-values-in-cells} + +Verwenden Sie den Parameter `marks` der Eigenschaft [`tableShape`](api/config/tableshape-property.md), um eine CSS-Klasse auf Zellen anzuwenden, die eine Bedingung erfüllen. Jeder Eintrag in `marks` verknüpft einen CSS-Klassenamen (den Schlüssel) mit einer Regel (dem Wert). + +Die Regel ist entweder ein vordefinierter String (`"max"` oder `"min"`) oder eine benutzerdefinierte Funktion `(value, columnData, rowData) => boolean`. Wenn die Funktion `true` zurückgibt, fügt Pivot die CSS-Klasse zur Zelle hinzu. + +Erstellen Sie die CSS-Klassen in Ihrem Stylesheet, bevor Sie `marks` anwenden. + +Das folgende Beispiel hebt Zellen mit den minimalen und maximalen Werten hervor und verwendet eine benutzerdefinierte Funktion, um Nicht-Ganzzahlen größer als 2 zu markieren: + +~~~jsx {18-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + marks: { + // integrierte Markierungen (Min/Max-Hervorhebung) + min_cell: "min", + max_cell: "max", + // benutzerdefinierte Markierung + g_avg: v => (v % 1 !== 0) && v > 2 + } + } +}); +~~~ + +Der folgende Code-Ausschnitt definiert die CSS-Klassen, auf die das `marks`-Objekt oben verweist: + +~~~html title="index.html" + +~~~ + +## Spezifische CSS-Klassen {#specific-css-classes} + +Pivot enthält mehrere CSS-Hilfsklassen, die Sie überschreiben können, um einzelne Tabellenelemente präzise zu steuern. + +Pivot richtet Zahlen in Body-Zellen über die integrierte CSS-Klasse `.wx-number` rechtsbündig aus. Ausnahme ist die hierarchische Spalte im Baumstruktur-Modus (wenn `tree: true` in [`tableShape`](api/config/tableshape-property.md) gesetzt ist). Um die Standard-Ausrichtung von Zahlen zurückzusetzen, überschreiben Sie die Klasse. + +Der folgende Code-Ausschnitt richtet Zahlen in Body-Zellen linksbündig aus: + +~~~html + +~~~ + +Um Gesamtspalten zu gestalten, überschreiben Sie die CSS-Klasse `.wx-total`. + +Der folgende Code-Ausschnitt gestaltet Gesamtzellen mit einem hellen Hintergrund und einer stärkeren Schriftgewichtung: + +~~~html + +~~~ + +## Beispiel {#example} + +Der folgende Ausschnitt wendet einen benutzerdefinierten Style auf Pivot an: + + + +**Verwandte Beispiele**: + +- [Pivot 2. Gestaltung (benutzerdefiniertes CSS) für die Gesamtspalte](https://snippet.dhtmlx.com/9lkdbzmm) +- [Pivot 2. Min/Max- und benutzerdefinierte Markierungen für Zellen (bedingte Formatierung)](https://snippet.dhtmlx.com/4cm4asbd) +- [Pivot 2. Alternierende Zeilenfarbe (gestreifte Zeilen, Zebra-Streifen)](https://snippet.dhtmlx.com/0cm0uko2) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/typescript-support.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/typescript-support.md new file mode 100644 index 0000000..5bea14a --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/typescript-support.md @@ -0,0 +1,17 @@ +--- +sidebar_label: TypeScript-Unterstützung +title: TypeScript-Unterstützung +description: Sie können in der Dokumentation erfahren, wie TypeScript mit der DHTMLX JavaScript Pivot-Bibliothek verwendet wird. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# TypeScript-Unterstützung {#typescript-support} + +DHTMLX Pivot wird ab v2.0 mit TypeScript-Definitionen geliefert. Die Definitionen sind sofort einsatzbereit – keine zusätzliche Konfiguration erforderlich. + +:::info +Testen Sie Pivot live im [Snippet-Tool](https://snippet.dhtmlx.com/y2buoahe). +::: + +## Vorteile von TypeScript {#advantages-of-typescript} + +Typprüfung und Autovervollständigung erkennen Fehler frühzeitig, und die mitgelieferten Definitionen zeigen Ihnen genau, welche Datentypen die DHTMLX Pivot-API erwartet. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/working-with-data.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/working-with-data.md new file mode 100644 index 0000000..6d6ad18 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/working-with-data.md @@ -0,0 +1,687 @@ +--- +sidebar_label: Arbeiten mit Daten +title: Arbeiten mit Daten +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie, wie Sie mit Daten arbeiten. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Arbeiten mit Daten + +Diese Seite beschreibt, wie Sie Daten in Pivot aggregieren, formatieren, sortieren, filtern und vorverarbeiten können. Anweisungen zum Laden und Exportieren von Daten finden Sie unter [Daten laden](guides/loading-data.md) und [Daten exportieren](guides/exporting-data.md). + +## Felder definieren {#define-fields} + +Verwenden Sie die Eigenschaft [`fields`](api/config/fields-property.md), um die Felder zu deklarieren, die Pivot in Zeilen, Spalten und Werten platzieren kann. Jedes Element im `fields`-Array beschreibt ein Feld — seine ID, sein Label und seinen Datentyp. + +Der folgende Code-Ausschnitt initialisiert Pivot mit fünf Feldern: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields: [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } + ], + data, + config: {...} +}); +~~~ + +## Formate auf Felder anwenden {#applying-formats-to-fields} + +Pivot wendet ein Standardformat auf numerische Felder und Datumsfelder basierend auf der aktuellen Locale an. Weitere Informationen finden Sie unter [Datumsformatierung](guides/localization.md#date-formatting) und [Zahlenformatierung](guides/localization.md#number-formatting). + +Um den Standard für ein bestimmtes Feld zu überschreiben, legen Sie den Parameter `format` der Eigenschaft [`fields`](api/config/fields-property.md) fest. + +### Numerische Felder formatieren {#format-numeric-fields} + +Verwenden Sie `prefix` und `suffix`, um Text um numerische Werte hinzuzufügen, und `maximumFractionDigits`, um die Dezimalgenauigkeit zu steuern. Um beispielsweise `12.345` als `"12.35 EUR"` darzustellen, setzen Sie das Suffix auf `" EUR"` und `maximumFractionDigits` auf `2`: + +~~~js +const fields = [ + { id: "sales", type: "number", format: { suffix: " EUR", maximumFractionDigits: 2 } }, +]; +~~~ + +Die Standardformatierung begrenzt numerische Felder auf 3 Nachkommastellen und wendet eine Gruppentrennzeichenformatierung auf den ganzzahligen Teil an. Um die Formatierung vollständig zu deaktivieren, setzen Sie `format` auf `false`: + +~~~js +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +Das folgende Beispiel markiert `marketing`, `profit` und `sales` als Währungsfelder mit einem `$`-Präfix und fixen 2-stelligen Dezimalstellen: + +~~~jsx +// Pivot mit einem vordefinierten Datensatz und Feldern initialisieren +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { field: "marketing", method: "sum" }, + // weitere Werte + + ], + }, + fields:[ + // benutzerdefiniertes Format + { id: "marketing", label: "Marketing", type:"number", format:{ + prefix: "$", minimumFractionDigits: 2, maximumFractionDigits: 2 } + } + ] +}); +~~~ + +### Datumsfelder formatieren {#format-date-fields} + +Um das locale-weite `dateFormat` für ein einzelnes Feld zu überschreiben, setzen Sie den Parameter `format` von [`fields`](api/config/fields-property.md) auf einen Datumsformat-String. + +Der folgende Code-Ausschnitt setzt `"%M %d, %Y"` als Format für das Feld `date`: + +~~~jsx +const fields = [ + { id: "date", type: "date", format: "%M %d, %Y" }, +]; +~~~ + +Das folgende Beispiel konvertiert String-Datumsangaben in `Date`-Objekte und initialisiert dann Pivot mit dem Format `"%d %M %Y %H:%i"` für das Feld `date`. Feldwerte werden als Labels wie `"24 April 2025 14:30"` dargestellt. + +~~~jsx +// Datums-Strings in Date-Objekte konvertieren +const dateFields = fields.filter(f => f.type === "date"); +dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v === "string") { + item[f.id] = new Date(v); + } + }); +}); + +// Pivot mit einem feldspezifischen Datumsformat initialisieren +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state"], + columns: ["product_type"], + values: [ + { field: "date", method: "min" }, + { field: "profit", method: "sum" }, + { field: "sales", method: "sum" } + ] + }, + fields:[ + // benutzerdefiniertes Format: Tag Monat Jahr Stunde:Minute + { id: "date", label: "Date", type: "date", format: "%d %M %Y %H:%i" } + ] +}); +~~~ + +:::note +Für das `xlsx`-Exportformat exportiert Pivot Datums- und Zahlenfelder als Rohwerte mit ihrem Standardformat (oder dem über die Eigenschaft [`fields`](api/config/fields-property.md) definierten Format). Wenn für ein Feld ein Template definiert ist (siehe die Eigenschaft [`tableShape`](api/config/tableshape-property.md)), exportiert Pivot den vom Template erzeugten gerenderten Wert. Wenn sowohl `template` als auch `format` gesetzt sind, überschreibt das Template das Format. +::: + +## Pivot-Struktur definieren {#define-pivot-structure} + +Verwenden Sie die Eigenschaft [`config`](api/config/config-property.md), um zu deklarieren, welche Felder als Zeilen, Spalten und aggregierte Werte erscheinen und wie die Daten gefiltert werden. Die Eigenschaft `config` hat keine vordefinierten Werte — Sie müssen sie setzen, um Daten zu rendern. Die vollständige Parameterliste finden Sie in der Referenz zu [`config`](api/config/config-property.md). + +Der folgende Code-Ausschnitt platziert `continent` und `name` in Zeilen, `year` in Spalten, drei Aggregationen in Werten und einen Filter auf `name`: + +~~~jsx {4-18} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }, + fields, + filters: { + name: { + contains: "B" + } + } +}); +~~~ + +## Daten sortieren {#sorting-data} + +Pivot unterstützt die Sortierung in allen drei Bereichen (Werte, Spalten, Zeilen) während der Aggregation. In der Benutzeroberfläche klicken Benutzer auf einen Spalten-Header, um zu sortieren. + +Um eine Standardsortierung festzulegen, verwenden Sie den Parameter `sort` der Eigenschaft [`fields`](api/config/fields-property.md). Der Parameter akzeptiert `"asc"`, `"desc"` oder eine benutzerdefinierte Vergleichsfunktion. + +Das folgende Beispiel rendert anklickbare Feld-Labels über Pivot und schaltet die Sortierreihenfolge beim Klicken um: + +~~~jsx +const bar = document.getElementById("bar"); + +let sorted = ["studio", "genre"]; +setFields(); +bar.addEventListener('click', (e) => switchSort(e.target.id), false); + +function setFields(){ + let html = ""; + let sortedFields = fields.filter(f => (sorted.indexOf(f.id) != -1)); + + sortedFields.forEach((f) =>{ + const order = f.sort || "asc"; + html += `
+ ${f.label} +
`; + }); + bar.innerHTML = html; +} + +function switchSort(id){ + fields.forEach(f => { + if(f.id == id){ + f.sort = f.sort != "desc" ? "desc" : "asc"; + } + }); + // Pivot-Felder aktualisieren + table.setConfig({ fields }); + // Icons aktualisieren + setFields(bar, fields); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +Die Sortierung in der Benutzeroberfläche ist standardmäßig aktiviert. Um sie zu deaktivieren, setzen Sie den Parameter `sort` der Eigenschaft [`columnShape`](api/config/columnshape-property.md) auf `false`. + +Der folgende Code-Ausschnitt deaktiviert die UI-Sortierung: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +## Daten filtern {#filtering-data} + +Pivot unterstützt Filter, die an Felddatentypen gebunden sind. Sie können Filter über die Pivot-Benutzeroberfläche nach der Initialisierung oder deklarativ über das `filters`-Objekt der Eigenschaft [`config`](api/config/config-property.md) setzen. + +In der Benutzeroberfläche erscheinen Filter als Dropdown-Listen für jedes Feld. + +#### Filtertypen {#filter-types} + +Pivot unterstützt die folgenden Filterbedingungen je Datentyp: + +- Textfelder — `equal`, `notEqual`, `contains`, `notContains`, `beginsWith`, `notBeginsWith`, `endsWith`, `notEndsWith`, `includes` +- Numerische Felder — `equal`, `notEqual`, `greater`, `greaterOrEqual`, `less`, `lessOrEqual`, `contains`, `notContains`, `beginsWith`, `notBeginsWith`, `endsWith`, `notEndsWith` +- Datumsfelder — `equal`, `notEqual`, `greater`, `greaterOrEqual`, `less`, `lessOrEqual`, `between`, `notBetween`, `includes` + +Die Regel `includes` schränkt einen Filter auf eine bestimmte Menge zulässiger Werte ein. + +#### Filter hinzufügen {#add-a-filter} + +Um einen Filter zu deklarieren, fügen Sie das `filters`-Objekt zur Eigenschaft [`config`](api/config/config-property.md) hinzu, mit der Feld-ID als Schlüssel. Jeder Wert ist ein Objekt mit Filterbedingungen. + +Der folgende Code-Ausschnitt wendet zwei Filter an — einen auf `genre` (Werte, die `"D"` enthalten, eingeschränkt auf `"Drama"`) und einen auf `title` (Werte, die `"A"` enthalten): + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // Filter für ein weiteres Feld ("title") + contains: "A" + } + } + } +}); +~~~ + +:::info +Um Daten stattdessen über die Table-Widget-API zu filtern, greifen Sie mit der Methode [`getTable`](api/methods/gettable-method.md) auf die Table-Instanz zu und verwenden Sie das Event [`filter-rows`](api/table/filter-rows.md). +::: + +## Geladene Daten begrenzen {#limiting-loaded-data} + +Um zu verhindern, dass die Komponente bei sehr großen Datensätzen hängt, begrenzen Sie die Anzahl der Zeilen und Spalten im finalen Datensatz mit der Eigenschaft [`limits`](api/config/limits-property.md). Pivot unterbricht das Rendering, sobald das Limit erreicht ist. Die Standardobergrenze liegt bei 10000 für Zeilen und 5000 für Spalten. + +:::note +Limits gelten für große Datensätze. Die Zahlen sind ungefähr — Pivot garantiert keine exakte Zeilen-/Spaltenanzahl. +::: + +Der folgende Code-Ausschnitt begrenzt den Datensatz auf 10 Zeilen und 3 Spalten: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + limits: { rows: 10, columns: 3 } +}); +~~~ + +## Mathematische Methoden anwenden {#applying-maths-methods} + +### Standardmethoden {#default-methods} + +Pivot enthält die folgenden integrierten Aggregationsmethoden: + +- `sum` (nur numerische Werte) — summiert alle ausgewählten Werte; ignoriert leere Zellen, logische Werte wie `TRUE` und Text +- `min` (numerische Werte und Datumswerte) — gibt den Minimalwert zurück; ignoriert leere Zellen, logische Werte und Text. Gibt `0` zurück, wenn die Eingabe keine Zahlen enthält +- `max` (numerische Werte und Datumswerte) — gibt den Maximalwert zurück; ignoriert leere Zellen, logische Werte und Text. Gibt `0` zurück, wenn die Eingabe keine Zahlen enthält +- `count` (numerische, Text- und Datumswerte) — zählt nicht leere Zellen; dies ist die Standardmethode, die jedem neu hinzugefügten Feld zugewiesen wird +- `countunique` (numerische Werte und Textwerte) — zählt die Anzahl eindeutiger Werte in der Eingabe +- `average` (nur numerische Werte) — berechnet das arithmetische Mittel der Eingabe; ignoriert leere Zellen, logische Werte und Text. Berücksichtigt Zellen mit dem Wert null +- `counta` (numerische, Text- und Datumswerte) — zählt alle nicht leeren Werte, einschließlich Zahlen, Datumsangaben und Text +- `median` (nur numerische Werte) — gibt den Median der Eingabe zurück +- `product` (nur numerische Werte) — gibt das Produkt aller Zahlen in der Eingabe zurück +- `stdev` (nur numerische Werte) — Standardabweichung, wobei die Eingabe als Stichprobe einer größeren Menge behandelt wird +- `stdevp` (nur numerische Werte) — Standardabweichung, wobei die Eingabe als die gesamte Population behandelt wird +- `var` (nur numerische Werte) — Varianz, wobei die Eingabe als Stichprobe einer größeren Menge behandelt wird +- `varp` (nur numerische Werte) — Varianz, wobei die Eingabe als die gesamte Population behandelt wird + +Der folgende Code-Ausschnitt zeigt die integrierten Methodendefinitionen: + +~~~jsx +const defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +Wenden Sie eine Standardmethode über den Parameter `values` der Eigenschaft [`config`](api/config/config-property.md) an. Siehe [Werte definieren](#options-for-defining-values). + +Der folgende Code-Ausschnitt weist dem Feld `title` die Methode `count` und dem Feld `score` die Methode `max` zu: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + // Feld-ID + field: "title", + // Methode + method: "count" + }, + { + id: "score", + method: "max" + } + ] + } +}); +~~~ + +### Werte definieren {#options-for-defining-values} + +Definieren Sie jeden Eintrag in `values` in einer von zwei äquivalenten Formen: + +- ein String der Form `"operation(fieldID)"` +- ein Objekt `{ field: string, method: string }` (beide Felder erforderlich) + +Der folgende Code-Ausschnitt verwendet beide Formen im selben `values`-Array: + +~~~jsx +values: [ + "sum(sales)", // Option eins + { field: "sales", method: "sum" } // Option zwei +] +~~~ + +### Die Standardmethode überschreiben {#override-the-default-method} + +Für jedes neu hinzugefügte Feld weist Pivot die erste verfügbare Methode für den Datentyp zu. Um dieses Verhalten zu ändern, fangen Sie das Event `add-field` mit der Methode [`api.intercept`](api/internal/intercept-method.md) ab. + +Das folgende Beispiel fängt `add-field` ab und erzwingt die Methode `max`, sobald ein numerisches Feld hinzugefügt wird: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count", + }, + { + field: "score", + method: "max", + }, + ], + }, +}); +// Standardmethode für neu hinzugefügte numerische Felder überschreiben +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "max"; + } +}); +~~~ + +### Benutzerdefinierte mathematische Methoden hinzufügen {#add-custom-math-methods} + +Um eine benutzerdefinierte Aggregationsmethode hinzuzufügen, verwenden Sie die Eigenschaft [`methods`](api/config/methods-property.md). Jeder Eintrag verknüpft einen Methodennamen (den Schlüssel) mit einem Konfigurationsobjekt, das eine `handler`-Funktion und Metadaten enthält. Der `handler` nimmt ein Array von Werten entgegen und gibt einen einzelnen aggregierten Wert zurück. + +Das folgende Beispiel fügt zwei datumsspezifische Methoden hinzu. `countunique_date` zählt eindeutige Datumsangaben anhand ihrer numerischen Zeitstempel. `average_date` gibt das durchschnittliche Datum zurück, indem Zeitstempel gemittelt werden: + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique", + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// Ganzzahlen für "count"- und "unique count"-Ergebnisse anzeigen +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// Datums-Strings in Date-Objekte konvertieren +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +## Daten mit Prädikaten verarbeiten {#processing-data-with-predicates} + +Prädikate sind Vorverarbeitungsfunktionen, die Rohfelddaten transformieren, bevor Pivot die Daten in Zeilen oder Spalten verwendet. Ein Prädikat kann beispielsweise Datumsangaben vor der Aggregation nach Monat gruppieren. + +Der folgende Code-Ausschnitt zeigt die integrierten Datumspr­ädikate, die Pivot standardmäßig anwendet: + +~~~jsx +const defaultPredicates = { + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +Um ein benutzerdefiniertes Prädikat hinzuzufügen, konfigurieren Sie die Eigenschaft [`predicates`](api/config/predicates-property.md). Jeder Eintrag verknüpft eine Prädikat-ID (den Schlüssel) mit einem Konfigurationsobjekt: + +- `type` — die Feldtypen, die dieses Prädikat akzeptiert (`"number"`, `"date"`, `"text"` oder ein Array) +- `label` — das Prädikat-Label, das im GUI-Dropdown für eine Zeile/Spalte angezeigt wird +- `handler` — Funktion, die einen Wert transformiert und den verarbeiteten Wert zurückgibt +- `template` — optionale Funktion, die steuert, wie der verarbeitete Wert angezeigt wird +- `field` — optionale Funktion, die das Prädikat auf bestimmte Felder beschränkt +- `filter` — optionale Filter-Konfiguration, wenn der Filtertyp vom `type` abweichen soll oder wenn das Datenformat vom `template` abweichen soll + +Um ein benutzerdefiniertes Prädikat zu verwenden, setzen Sie seine ID als `method` der Zeile oder Spalte, auf die das Prädikat angewendet werden soll. + +Der folgende Code-Ausschnitt registriert zwei benutzerdefinierte Prädikate (`monthYear` und `profitSign`) und wendet sie in der `columns`-Konfiguration an: + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// Datums-Strings in Date-Objekte konvertieren +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +## Spalten und Zeilen mit Gesamtwerten hinzufügen {#add-columns-and-rows-with-total-values} + +Verwenden Sie die Eigenschaft [`tableShape`](api/config/tableshape-property.md), um eine Gesamtspalte rechts (`totalColumn: true`) oder eine Gesamtzeile als Fußzeile (`totalRow: true`) zu rendern. + +Der folgende Code-Ausschnitt aktiviert sowohl die Gesamtspalte als auch die Gesamtzeile: + +~~~jsx {2-5} +const table = new pivot.Pivot("#root", { + tableShape: { + totalRow: true, + totalColumn: true + }, + fields, + data, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + } + ] + } +}); +~~~ + +## Beispiel {#example} + +Der folgende Ausschnitt wendet benutzerdefinierte mathematische Operationen an: + + + +**Verwandte Beispiele**: + +- [Pivot 2. Datensatz mit Aliasen](https://snippet.dhtmlx.com/7vc68rqd) +- [Pivot 2. Feldformate definieren](https://snippet.dhtmlx.com/77nc4j8v) +- [Pivot 2. Externer Filter](https://snippet.dhtmlx.com/s7tc9g4z) +- [Pivot 2. Gesamtsumme für Spalten und Zeilen](https://snippet.dhtmlx.com/f0ag0t9t) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/working-with-server.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/working-with-server.md new file mode 100644 index 0000000..2e19094 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/working-with-server.md @@ -0,0 +1,172 @@ +--- +sidebar_label: Mit dem Server arbeiten +title: Mit dem Server arbeiten +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie, wie Sie Pivot in ein Backend integrieren. Erkunden Sie Entwicklerleitfäden und die API-Referenz, testen Sie Code-Beispiele und Live-Demos, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +Pivot läuft vollständig im Browser. Das Widget nimmt ein Array aus rohen Zeilen sowie eine [`config`](/api/config/config-property) (Rows / Columns / Values) entgegen und aggregiert die Zeilen clientseitig. Es gibt keine integrierte Transport-Schicht, aber die öffentliche API stellt Hooks für die Kommunikation mit einem beliebigen Backend bereit. + +Eine typische Integration umfasst drei Teile: + +1. **Laden** von rohen, nicht aggregierten Daten vom Server bei der Initialisierung +2. **Speichern der Config**, wenn der Benutzer das Layout ändert, damit die Sitzung später fortgesetzt werden kann +3. **Speichern der aggregierten Tabelle**, wenn der Server einen Snapshot des zusammengefassten Ergebnisses benötigt + +## Rohdaten vom Server laden {#load-raw-data-from-the-server} + +Die [`data`](/api/config/data-property)-Eigenschaft erwartet ein Array aus rohen Zeilenobjekten. Pivot aggregiert die Zeilen selbst, daher gibt der Server nicht aufbereitete Daten zurück. + +Rufen Sie Daten und Felder mit `fetch` (oder einem beliebigen HTTP-Client) ab und erstellen Sie das Widget, sobald die Antwort eintrifft: + +~~~html +
+ + +~~~ + +Wenn der Server Datumsfelder als ISO-Strings zurückgibt, konvertieren Sie diese in `Date`-Instanzen, bevor Sie das Array an Pivot übergeben. Aggregationsmethoden für datumsbasierte Felder erfordern echte `Date`-Werte: + +~~~jsx +data.forEach(row => { + if (typeof row.when === "string") row.when = new Date(row.when); +}); +~~~ + +:::info +**Siehe auch**: +- [Daten laden](/guides/loading-data) +- [Datumsformatierung](/guides/localization#date-formatting) +::: + +## Layout des Benutzers speichern, um die Sitzung fortzusetzen {#save-the-users-layout-to-resume-the-session} + +Damit Benutzer zu dem Layout zurückkehren können, das sie zuletzt verwendet haben, speichern Sie das [`config`](/api/config/config-property)-Objekt bei jeder Änderung. Das [`update-config`](/api/events/update-config-event)-Event wird ausgelöst, wenn der Benutzer das Layout über die Benutzeroberfläche bearbeitet. Der Payload ist die verarbeitete Config mit der Struktur `{ rows, columns, values, filters }`. + +Verwenden Sie [`api.on()`](/api/internal/on-method), um das Event zu beobachten, ohne es zu modifizieren. Wechseln Sie zu [`api.intercept()`](/api/internal/intercept-method), wenn der Handler den Event-Payload ändern muss. + +Das folgende Beispiel abonniert das `update-config`-Event und sendet das neue Layout an den Server: + +~~~html +
+ + +~~~ + +Beim nächsten Besuch geben Sie die gespeicherte Config von `/config` zurück und übergeben sie beim Start als `config`-Eigenschaft. Das Widget startet mit dem vorherigen Layout. Falls das Layout nach der Erstellung des Widgets eintrifft, wenden Sie die gespeicherte Config mit der Methode [`setConfig()`](/api/methods/setconfig-method) an. + +Häufige Aktualisierungen können den Server überlasten, wenn der Benutzer Felder im Konfigurationspanel verschiebt. Schließen Sie den POST in einen Timer ein, um die Aufrufe zu entprellen: + +~~~jsx +let saveTimer; +table.api.on("update-config", newConfig => { + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/config", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(newConfig), + }); + }, 300); +}); +~~~ + +:::note +Der `update-config`-Payload ist die *verarbeitete* Konfiguration: Pivot kann Feldreferenzen in die Form `{ field, method }` normalisieren. Senden Sie die verarbeitete Struktur beim Start als `config`-Eigenschaft zurück. Eine zusätzliche Konvertierung ist nicht erforderlich. +::: + +:::tip +Geben Sie `false` aus dem Handler zurück, um die Layout-Änderung zu blockieren. Nutzen Sie dies, um die Persistenz an eine serverseitige Validierung zu knüpfen. +::: + +## Aggregierte Tabelle speichern {#save-the-aggregated-table} + +Manchmal ist das *Ergebnis* selbst der Wert: ein serverseitiger Cache der gerenderten Tabelle, ein regelmäßiger Bericht oder eine Export-Pipeline. Das [`render-table`](/api/events/render-table-event)-Event wird ausgelöst, nachdem Pivot die Aggregation abgeschlossen hat, und enthält die vollständig zusammengefasste Tabelle: `columns`, `data`-Zeilen, `footer`, `split` und weitere Felder. + +Das folgende Beispiel abonniert `render-table` und sendet den Snapshot an den Server, wobei das erste Rendering übersprungen wird: + +~~~jsx +const table = new pivot.Pivot("#root", { data, fields, config }); + +let firstRender = true; +let saveTimer; + +table.api.on("render-table", ({ config: tableConfig }) => { + // erstes Rendering überspringen, das durch die erste Aggregation ausgelöst wird + if (firstRender) { + firstRender = false; + return; + } + + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/snapshot", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + columns: tableConfig.columns, + data: tableConfig.data, + footer: tableConfig.footer, + split: tableConfig.split, + }), + }); + }, 300); +}); +~~~ + +:::note +Das `render-table`-Event wird häufiger ausgelöst als `update-config`. Das Event läuft bei jeder Neuberechnung, einschließlich Sortierung und Auf-/Zuklappen. Entprellen Sie den Handler und überspringen Sie das erste Rendering, um nur einen POST pro tatsächlicher Änderung zu senden. +::: + +:::tip +Geben Sie `false` aus dem Handler zurück, um das Rendering zu verhindern. Nutzen Sie dies, wenn der Server den Snapshot ablehnt oder für Nur-Lese-Modi. +::: + +### Aggregierten Snapshot neu laden {#reload-an-aggregated-snapshot} + +Pivot erstellt aggregierte Tabellen und zeigt keine voraggregtierten an. Die [`data`](/api/config/data-property)-Eigenschaft akzeptiert immer rohe Zeilen. Ein aus `render-table` gespeicherter Snapshot eignet sich daher für folgende Anwendungsfälle: + +- eine nachgelagerte Export-Pipeline (CSV, XLSX) auf dem Server +- eine Nur-Lese-Ansicht, die von einer einfachen Datentabelle aus den gespeicherten `columns` und `data` gerendert wird +- ein zwischengespeicherter Bericht, der anderen Benutzern bereitgestellt wird, ohne die Aggregation erneut auszuführen + +**Verwandte Artikel**: + +- [Daten laden](/guides/loading-data) +- [Daten exportieren](/guides/exporting-data) + +**Verwandte API**: + +- [`api.on()`](/api/internal/on-method) +- [`update-config`](/api/events/update-config-event) +- [`render-table`](/api/events/render-table-event) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/how-to-start.md b/i18n/de/docusaurus-plugin-content-docs/current/how-to-start.md new file mode 100644 index 0000000..5a413b9 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/how-to-start.md @@ -0,0 +1,122 @@ +--- +sidebar_label: Erste Schritte +title: Erste Schritte +description: Erfahren Sie, wie Sie mit DHTMLX Pivot arbeiten – in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek. Durchsuchen Sie Entwicklerleitfäden und API-Referenzen, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Erste Schritte {#how-to-start} + +Dieses klare und umfassende Tutorial führt Sie durch die Schritte, die erforderlich sind, um ein voll funktionsfähiges Pivot auf einer Seite einzurichten. + +![pivot-main](/assets/pivot_main.png) + +## Schritt 1. Pakete herunterladen und installieren {#step-1-downloading-and-installing-packages} + +[Laden Sie das Paket herunter](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml) und entpacken Sie es in einen Ordner Ihres Projekts. + +Sie können JavaScript Pivot mit dem Paketmanager `yarn` oder `npm` in Ihr Projekt importieren. + +:::info +Wenn Sie Pivot in React-, Angular-, Svelte- oder Vue-Projekte integrieren möchten, lesen Sie die entsprechenden [**Integrationsleitfäden**](/category/integration-with-frameworks/) für weitere Informationen. +::: + +### Trial-Version von Pivot über npm oder yarn installieren {#installing-trial-pivot-via-npm-or-yarn} + +:::info +Wenn Sie die Trial-Version von Pivot verwenden möchten, laden Sie das [**Trial-Pivot-Paket**](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml) herunter und folgen Sie den im *README*-Datei beschriebenen Schritten. Beachten Sie, dass die Trial-Version von Pivot nur 30 Tage lang verfügbar ist. +::: + +### PRO-Version von Pivot über npm oder yarn installieren {#installing-pro-pivot-via-npm-or-yarn} + +:::info +Sie können direkt im [Kundenbereich](https://dhtmlx.com/clients/) auf das private DHTMLX-**npm** zugreifen, indem Sie Ihre Anmeldedaten für **npm** generieren. Eine detaillierte Installationsanleitung ist dort ebenfalls verfügbar. Bitte beachten Sie, dass der Zugriff auf das private **npm** nur während einer aktiven proprietären Pivot-Lizenz möglich ist. +::: + +## Schritt 2. Quelldateien einbinden {#step-2-including-source-files} + +Erstellen Sie zunächst eine HTML-Datei und nennen Sie sie *index.html*. Binden Sie anschließend die Pivot-Quelldateien in die erstellte Datei ein. + +Zwei Dateien sind erforderlich: + +- die JS-Datei von Pivot +- die CSS-Datei von Pivot + +~~~html {5-6} title="index.html" + + + + How to Start with Pivot + + + + + + + +~~~ + +## Schritt 3. Pivot erstellen {#step-3-creating-pivot} + +Jetzt können Sie Pivot zur Seite hinzufügen. Erstellen Sie zunächst den DIV-Container für Pivot. + +~~~html {} title="index.html" + + + + How to Start with Pivot + + + + +
+ + + +~~~ + +## Schritt 4. Pivot konfigurieren {#step-4-configuring-pivot} + +Als Nächstes können Sie die Konfigurationseigenschaften festlegen, die die Pivot-Komponente bei der Initialisierung haben soll. + +Um mit Pivot zu arbeiten, müssen Sie zunächst die Ausgangsdaten bereitstellen. Das folgende Beispiel erstellt ein Pivot mit: + +- Zeilen für *studio* und *genre* +- der Spalte *title* +- der Wertaggregation für *score* mit der Methode *max* + +Das Array **fields** ist erforderlich, um die Feld-IDs, Anzeigelabels und Datentypen zu definieren. + +Das Array **data** soll die tatsächlichen Daten enthalten, die im Pivot-Widget angezeigt werden. Jedes Objekt im Array repräsentiert eine Zeile in der Tabelle. + +Das Objekt **config** definiert die Struktur der Pivot-Tabelle, d. h. welche Felder als Zeilen und Spalten der Tabelle verwendet werden und welche Datenaggregationsmethoden auf die Felder angewendet werden sollen. + +~~~jsx +const table = new pivot.Pivot("#root", { + //Konfigurationseigenschaften + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## Wie geht es weiter {#whats-next} + +Das war's. Mit diesen einfachen Schritten verfügen Sie über ein praktisches Werkzeug zur Datenanalyse. Jetzt können Sie mit Ihren Aufgaben beginnen oder die Welt von JavaScript Pivot weiter erkunden: + +- Die Seiten [Leitfäden](/category/guides) enthalten Anleitungen zur Installation, zum Laden von Daten, zur Gestaltung und weitere hilfreiche Tipps für eine reibungslose Pivot-Konfiguration +- Die [API-Referenz](api/overview/main-overview.md) beschreibt die Funktionalität von Pivot diff --git a/i18n/de/docusaurus-plugin-content-docs/current/index.md b/i18n/de/docusaurus-plugin-content-docs/current/index.md new file mode 100644 index 0000000..bddb34c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/index.md @@ -0,0 +1,103 @@ +--- +sidebar_label: Pivot-Übersicht +title: JavaScript Pivot – Übersicht +slug: / +description: In dieser Dokumentation erhalten Sie einen Überblick über die DHTMLX JavaScript Pivot-Bibliothek. Durchsuchen Sie Entwicklerhandbücher und die API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# DHTMLX Pivot – Übersicht {#dhtmlx-pivot-overview} + +Die JavaScript Pivot-Bibliothek ist eine fertige Komponente zur Erstellung von Pivot-Tabellen aus großen Datensätzen. Die Widget-API lässt sich problemlos an die Anforderungen Ihrer Webanwendung anpassen. Sie bietet dem Endbenutzer Funktionen zum Vergleichen und Analysieren komplexer Daten innerhalb einer einzigen Tabelle. + +## Aufbau von Pivot {#pivot-structure} + +Die Pivot-Oberfläche besteht aus zwei Hauptkomponenten: dem Konfigurationsbereich und der Datentabelle. + +![Main](assets/pivot-main.png) + +## Konfigurationsbereich {#configuration-panel} + +Im Konfigurationsbereich können Sie der Tabelle Spalten und Zeilen sowie Wertefelder hinzufügen, die die Datenaggregationsmethoden festlegen. Jedes Element lässt sich über die folgenden Bereiche im Panel hinzufügen: + +- Werte: Sie können Werte hinzufügen, die bestimmen, wie Daten aggregiert werden (z. B. Summe, Minimum, Maximum) +- Spalten: Sie können die Spalten der Tabelle konfigurieren (festlegen, welche Felder als Spalten verwendet werden) +- Zeilen: Sie können festlegen, welche Felder als Zeilen der Tabelle verwendet werden sollen + +Um den Konfigurationsbereich auszublenden, klicken Sie auf die Schaltfläche **Einstellungen ausblenden**: + +![config_panel](assets/config_panel.png) + +### Wertebereich {#values-area} + +Im **Wertebereich** können Sie festlegen, welche Aggregationsmethoden (z. B. Minimum, Maximum, Anzahl) auf die Zellen der Pivot-Tabelle angewendet werden. Sie können folgende Operationen ausführen: + +- Felder zum Wertebereich hinzufügen und daraus entfernen +- Reihenfolge und Priorität der Werte in der Tabelle ändern +- Daten filtern +- Operationen festlegen, die auf die Felder der Tabelle angewendet werden + +Weitere Einzelheiten finden Sie in den Abschnitten [Operationen in Bereichen](#operations-in-areas) und [Filter](#filters). + +### Spaltenbereich {#columns-area} + +Im **Spaltenbereich** können Sie folgende Operationen ausführen: + +- Spalten hinzufügen und entfernen (d. h. als Spalten verwendete Felder hinzufügen/entfernen) +- Reihenfolge und Priorität der Spalten in der Tabelle ändern +- Daten filtern + +Weitere Einzelheiten finden Sie in den Abschnitten [Operationen in Bereichen](#operations-in-areas) und [Filter](#filters). + +### Zeilenbereich {#rows-area} + +Im Konfigurationsbereich für den **Zeilenbereich** können Sie folgende Operationen ausführen: + +- Zeilen hinzufügen und entfernen (d. h. als Zeilen verwendete Felder hinzufügen/entfernen) +- Reihenfolge und Priorität der Zeilen in der Tabelle ändern +- Daten filtern + +Weitere Einzelheiten finden Sie in den Abschnitten [Operationen in Bereichen](#operations-in-areas) und [Filter](#filters). + +### Operationen in Bereichen {#operations-in-areas} + +In allen drei Bereichen des Konfigurationsbereichs können Sie Felder zur Tabelle hinzufügen und daraus entfernen. Wenn ein Feld als Zeile oder Spalte verwendet werden soll, wählen Sie es im entsprechenden Bereich (Spalten oder Zeilen) aus. + +Um ein neues Feld hinzuzufügen, klicken Sie im gewünschten Bereich auf die Schaltfläche „+" und wählen Sie den Namen aus der Dropdown-Liste aus. + +Um ein Element zu entfernen, klicken Sie auf die Löschen-Schaltfläche („x"). + +![add_remove](assets/add_remove.png) + +Um die Reihenfolge von Werten, Zeilen oder Spalten in der Tabelle zu ändern, ziehen Sie ein Element an die gewünschte Position. Je weiter links sich ein Element in der Symbolleistenliste des Bereichs befindet, desto höher ist seine Priorität und Position in der Tabelle. + +![priority](assets/priority.png) + +Um Operationen festzulegen, die auf alle Daten einer Tabellenspalte angewendet werden, klicken Sie im **Wertebereich** auf die Wertoperation des gewünschten Felds in der Dropdown-Liste und wählen Sie die gewünschte Option aus der Liste aus. + +![operations](assets/operations.png) + +### Filter {#filters} + +Filter werden als Dropdown-Listen für jedes Feld in allen Bereichen angezeigt. Pivot unterstützt die folgenden Bedingungstypen zum Filtern: + +- für Textwerte: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith +- für numerische Werte: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains, begins with, not begins with, ends with, not ends with +- für Datumstypen: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween + +Um Daten in der Tabelle zu filtern, klicken Sie auf das Filtersymbol eines der Elemente im gewünschten Bereich, wählen Sie dann den Operator aus, legen Sie den Filterwert fest und klicken Sie auf **Anwenden**. Felder, auf die eine Filterung angewendet wird, werden mit einem speziellen Filtersymbol markiert. + +![filters](assets/filter.png) + +## Tabelle {#table} + +Die Daten in der Tabelle werden so angezeigt, wie sie im Konfigurationsbereich eingestellt wurden. Die **Sortierung** in Spalten wird durch Klicken auf den Spaltenheader aktiviert: + +![table](assets/table.png) + +## Nächste Schritte {#whats-next} + +Jetzt können Sie mit der Integration von Pivot in Ihre Anwendung beginnen. Folgen Sie den Anweisungen im Tutorial [Erste Schritte](how-to-start.md). + +Wenn Sie die vom Widget-API bereitgestellten Funktionen nutzen, erhalten Sie eine ansprechende Pivot-Tabelle mit weiteren Features, wie in dem folgenden Beispiel zu sehen: + + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/news/migration.md b/i18n/de/docusaurus-plugin-content-docs/current/news/migration.md new file mode 100644 index 0000000..d4ef74f --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/news/migration.md @@ -0,0 +1,57 @@ +--- +sidebar_label: Migration zu neueren Versionen +title: Migration zu neueren Versionen +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die Migration zu neueren Versionen. Erkunden Sie Entwicklerleitfäden und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Migration zu neueren Versionen + +## 2.0 -> 2.1 + +- Der Parameter `colWidth` des `sizes`-Objekts in der Eigenschaft `tableShape` wurde in `columnWidth` umbenannt + +## 1.5 -> 2.0 + +Diese Liste der Änderungen hilft Ihnen bei der Migration von der vorherigen Version Pivot 1.5 zur vollständig erneuerten Version Pivot 2.0 + +:::note +Prüfen Sie unseren [Konverter für die Datenmigration von v.1.5](https://snippet.dhtmlx.com/s4sfdhq4) +::: + +### Geänderte API {#changed-api} + +#### Eigenschaften {#properties} + +Neue Eigenschaften sind keine vollständige Duplikate der vorherigen, sondern bieten erweiterte Funktionalität. + +- [fieldList](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldlist_config.html) -> [fields](api/config/fields-property.md) +- [fields](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fields_config.html) -> [config](api/config/config-property.md) +- [mark](https://docs.dhtmlx.com/pivot/1-5/api__pivot_mark_config.html) -> der Parameter `marks` der Eigenschaft [tableShape](api/config/tableshape-property.md) +- [types](https://docs.dhtmlx.com/pivot/1-5/api__pivot_types_config.html) -> [methods](api/config/methods-property.md) +- [layout](https://docs.dhtmlx.com/pivot/1-5/api__pivot_layout_config.html) -> [columnShape](api/config/columnshape-property.md), [headerShape](api/config/headershape-property.md), [readonly](api/config/readonly-property.md) +- [customFormat](https://docs.dhtmlx.com/pivot/1-5/api__pivot_customformat_config.html) -> [predicates](api/config/predicates-property.md) - benutzerdefinierte Vorverarbeitungsfunktionen für Daten + +#### Events {#events} + +- [filterApply](https://docs.dhtmlx.com/pivot/1-5/api__pivot_filterapply_event.html) -> [apply-filter](api/events/apply-filter-event.md) +- [fieldClick](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldclick_event.html) -> es gibt kein identisches Event, aber Sie können [update-field](api/events/update-field-event.md) verwenden + +### Entfernte API {#removed-api} + +- [Methoden aus Version 1.5](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_methods.html) sind veraltet; alle neuen Methoden finden Sie hier: [Methoden](api/overview/main-overview.md#pivot-methods) +- [Pivot-1.5-Events](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_events.html) (`change`, `fieldClick`, `applyButtonClick`) sind in Pivot 2.0 nicht mehr verfügbar, aber Sie finden in der neuen Version erweiterte Funktionalität (siehe [Pivot-Events](api/overview/events-overview.md)) + +### Wichtige Features {#important-features} + +- Datenexport: [frühere Export-Option](https://docs.dhtmlx.com/pivot/1-5/guides__export.html) -> [neue Export-Option](guides/exporting-data.md) +- Sortierung: [Felder sortieren](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringfields) -> [Daten sortieren](guides/working-with-data.md#sorting-data) +- Baumstruktur-Modus: [gridMode](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#gridmode) -> [Baumstruktur-Modus aktivieren](guides/configuration.md#enabling-the-tree-mode) +- Datumsformat: [Datumsfelder konfigurieren](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringdatefields) -> +[Datumsformat festlegen](guides/localization.md#date-formatting) +- Anpassung: + - [Zellenformatierung](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#conditionalformattingofcells) -> [Zellenstil](guides/stylization.md#cell-style) + - [Vorlagen für Kopfzeilen](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforheaders) -> + [Vorlagen auf Kopfzeilen anwenden](guides/configuration.md#applying-templates-to-headers) + - [Vorlagen für Zellen](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforcells) -> + [Vorlagen auf Zellen anwenden](guides/configuration.md#applying-templates-to-cells) +- Filterung: [Arbeiten mit Filtern](https://docs.dhtmlx.com/pivot/1-5/guides__using_filters.html) -> [Daten filtern](guides/working-with-data.md#filtering-data) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/news/whats-new.md b/i18n/de/docusaurus-plugin-content-docs/current/news/whats-new.md new file mode 100644 index 0000000..2a7ce40 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/news/whats-new.md @@ -0,0 +1,114 @@ +--- +sidebar_label: Was ist neu +title: Was ist neu +description: Sie können erkunden, was neu in DHTMLX Pivot ist, und die Release-Historie in der Dokumentation der DHTMLX JavaScript-UI-Bibliothek nachschlagen. Durchsuchen Sie Entwicklerhandbücher und API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Was ist neu {#whats-new} + +Wenn Sie Pivot von einer älteren Version aktualisieren, lesen Sie [Migration zu neueren Versionen](news/migration.md) für Details. + +## Version 2.1.1 {#version-211} + +Veröffentlicht am 10. Juni 2026 + +### Fehlerbehebungen {#fixes} + +- Der Fehler „getMonth" tritt auf, wenn Zeilenfilter auf Datensätze mit fehlenden oder leeren Werten angewendet werden + +## Version 2.1 {#version-21} + +Veröffentlicht am 6. Mai 2025 + +### Neue Funktionalität {#new-functionality} + +- [Möglichkeit, Spalten rechts einzufrieren](guides/configuration.md#freezing-columns-on-the-right) +- [Standardausrichtung](guides/stylization.md#specific-css-classes) und [gebietsschemabasierte Formatierung](guides/localization.md#number-formatting) für numerische Werte +- [Möglichkeit, benutzerdefinierte Zahlenformate zu definieren](guides/working-with-data.md#applying-formats-to-fields) (für Datums- und Zahlenfelder) über `format` in der Eigenschaft [`fields`](api/config/fields-property.md) +- [Möglichkeit, Header- und Tabellenzellen zu gestalten](guides/stylization.md#cell-style) über den Parameter `cellStyle` der Eigenschaften [`tableShape`](api/config/tableshape-property.md) und [`headerShape`](api/config/headershape-property.md) +- Möglichkeit, HTML-Inhalt in Header- und Tabellenzellen über den Helfer [`pivot.template`](api/helpers/template.md) einzufügen, indem ein Template als `cell`-Eigenschaft der Header- und Spaltenobjekte definiert wird (Tabellenanpassung durch Abfangen des Events [render-table](api/events/render-table-event.md)) +- [Excel- und CSV-Exporteinstellungen erweitert](guides/exporting-data.md): + - Für das Format „xlsx" werden Datums- und Zahlenfelder als Rohwerte mit Standardformat oder dem über die Eigenschaft [`fields`](api/config/fields-property.md) definierten Format exportiert + - Möglichkeit, Datei- und Sheetnamen zu definieren und Header/Footer aus einer exportierten Datei auszuschließen + - Möglichkeit, Stile und Templates für exportierte Zellen hinzuzufügen +- [Möglichkeit, Daten über eine externe Eingabe zu filtern](api/table/filter-rows.md) +- Visueller Rahmen für die Zellennavigation +- [Integration mit Frameworks](/category/integration-with-frameworks) + +### Neue API {#new-api} + +- Einstellung `right` innerhalb des Objekts `split` der Eigenschaft [`tableShape`](api/config/tableshape-property.md) +- Einstellung `cellStyle` innerhalb der Eigenschaften [`tableShape`](api/config/tableshape-property.md) und [`headerShape`](api/config/headershape-property.md) +- Einstellung `format` innerhalb des Arrays [`fields`](api/config/fields-property.md) +- Event [`filter-rows`](api/table/filter-rows.md) der internen Tabelle +- [`pivot.template`](api/helpers/template.md) zur Definition von HTML-Inhalt für Tabellenzellen + +### Fehlerbehebungen {#fixes-21} + +- Gesamtspalten werden nicht sortiert +- Zeichenfolgenwerte mit führender 0 werden beim Export in Zahlen umgewandelt +- Das Predicate-Template wird nicht auf Zeilen/Spalten angewendet +- Resize-Observer-Fehler in Grenzfällen + +### Breaking Changes {#breaking-changes} + +- Der Parameter `colWidth` des Objekts `sizes` in der Eigenschaft `tableShape` wurde in `columnWidth` umbenannt + +## Version 2.0.3 {#version-203} + +Veröffentlicht am 29. November 2024 + +### Fehlerbehebungen {#fixes-203} + +- Export von Baumstrukturen nach Excel/CSV enthält nur die obersten Ebenen +- Exportierte Spalten mit Autobreite sind in der resultierenden Excel-Datei zu schmal +- Falsche Position eines Popups mit Filtern +- Falsches Verhalten nach dem Ändern der Konfiguration mit der Methode setConfig +- Präzisere Typdefinitionen + +## Version 2.0.2 {#version-202} + +Veröffentlicht am 22. Oktober 2024 + +### Fehlerbehebungen {#fixes-202} + +- Typdefinition `columnShape` +- Korrekter Paketinhalt + +## Version 2.0 {#version-20} + +Veröffentlicht am 26. August 2024 + +Bitte lesen Sie die Übersicht der Version auf [der Blog-Seite](https://dhtmlx.com/blog/) + +### Breaking Change {#breaking-change} + +:::note +Die API von Version 1.5 ist nicht kompatibel mit API v.2.0. +::: + +Tipps zur Migration auf die neue Version finden Sie auf der Seite [Migration](news/migration.md). + +### Neue Funktionalität {#new-functionality-20} + +- Pivot 2.0 ist schnell beim Rendern und Generieren großer Datensätze ([Beispiel](https://snippet.dhtmlx.com/e6qwqrys)) +- Neue Funktionen zur Konfiguration von Aussehen und Verhalten der Spalten sind über die Eigenschaft [`columnShape`](api/config/columnshape-property.md) verfügbar: + - Einstellung von **autowidth** mit der Möglichkeit, die maximalen Zeilen für die **autoWidth**-Berechnung festzulegen ([Beispiel](https://snippet.dhtmlx.com/tn1yw14m)) + - Das Feature **firstOnly**, bei dem jedes Feld der gleichen Daten nur einmal analysiert wird, um die Spaltenbreite zu berechnen (standardmäßig) +- Jetzt können Sie das Aussehen und das Verhalten von Headern über die Eigenschaft [`headerShape`](api/config/headershape-property.md) konfigurieren, die Folgendes ermöglicht: + - Anwenden eines Templates auf den Text in Headern ([Beispiel](https://snippet.dhtmlx.com/g89r9ryw)) + - Ändern der Textausrichtung ([Beispiel](https://snippet.dhtmlx.com/4qroi8ka)) + - Spalten einklappbar machen ([Beispiel](https://snippet.dhtmlx.com/pt2ljmcm)) +- Form und Größen der Tabelle können über die Eigenschaft [`tableShape`](api/config/tableshape-property.md) konfiguriert werden, die Folgendes ermöglicht: + - Konfigurieren der Höhe von Zeilen, Headern, Footer: rowHeight, headerHeight, footerHeight ([Größenänderung der Tabelle](guides/configuration.md#resizing-the-table)) + - Generieren von Gesamtwerten nicht nur für Spalten, sondern auch für Zeilen, was über den Parameter **totalColumn** der Eigenschaft `tableShape` ermöglicht wird ([Beispiel](https://snippet.dhtmlx.com/f0ag0t9t)) + - Ausblenden doppelter Werte in der Tabellenansicht (der Parameter **cleanRows** der Eigenschaft [`tableShape`](api/config/tableshape-property.md)) + - Spalten von links fixieren, sodass sie beim Scrollen statisch bleiben ([Beispiel](https://snippet.dhtmlx.com/lahf729o)) + - Alle Zeilen auf- oder zuklappen ([Beispiel](https://snippet.dhtmlx.com/i4mi6ejn)) +- Weitere Funktionen zum Aggregieren von Daten wurden hinzugefügt: + - [Begrenzen geladener Daten](guides/working-with-data.md#limiting-loaded-data) + - Mehr [Operationen mit Daten](guides/working-with-data.md#applying-maths-methods) sind verfügbar + - [Daten mit Predicates verarbeiten](guides/working-with-data.md#processing-data-with-predicates) – Anwenden benutzerdefinierter Vorverarbeitungsfunktionen für Daten + - [Datumsformat über Gebietsschema festlegen](guides/localization.md#date-formatting) +- Neue Methoden wurden hinzugefügt: [`getTable()`](api/methods/gettable-method.md), [`setConfig()`](api/methods/setconfig-method.md), [`setLocale()`](api/methods/setlocale-method.md), [`showConfigPanel()`](api/methods/showconfigpanel-method.md) +- Neue Events wurden hinzugefügt: [`add-field`](api/events/add-field-event.md), [`delete-field`](api/events/delete-field-event.md), [`open-filter`](api/events/open-filter-event.md), [`render-table`](api/events/render-table-event.md), [`move-field`](api/events/move-field-event.md), [`show-config-panel`](api/events/show-config-panel-event.md), [`show-config-panel`](api/events/show-config-panel-event.md), [`update-config`](api/events/update-config-event.md), [`update-field`](api/events/update-field-event.md). diff --git a/i18n/de/docusaurus-theme-classic/footer.json b/i18n/de/docusaurus-theme-classic/footer.json new file mode 100644 index 0000000..4f1794a --- /dev/null +++ b/i18n/de/docusaurus-theme-classic/footer.json @@ -0,0 +1,62 @@ +{ + "link.title.Development center": { + "message": "Entwicklungszentrum", + "description": "The title of the footer links column with title=Development center in the footer" + }, + "link.title.Community": { + "message": "Community", + "description": "The title of the footer links column with title=Community in the footer" + }, + "link.title.Company": { + "message": "Unternehmen", + "description": "The title of the footer links column with title=Company in the footer" + }, + "link.item.label.Download JS Pivot": { + "message": "JS Pivot herunterladen", + "description": "The label of footer link with label=Download JS Pivot linking to https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml" + }, + "link.item.label.Examples": { + "message": "Beispiele", + "description": "The label of footer link with label=Examples linking to https://snippet.dhtmlx.com/mhymus00?tag=pivot" + }, + "link.item.label.Blog": { + "message": "Blog", + "description": "The label of footer link with label=Blog linking to https://dhtmlx.com/blog/tag/pivot/" + }, + "link.item.label.Forum": { + "message": "Forum", + "description": "The label of footer link with label=Forum linking to https://forum.dhtmlx.com/c/pivot/16" + }, + "link.item.label.GitHub": { + "message": "GitHub", + "description": "The label of footer link with label=GitHub linking to https://github.com/DHTMLX" + }, + "link.item.label.Youtube": { + "message": "Youtube", + "description": "The label of footer link with label=Youtube linking to https://www.youtube.com/user/dhtmlx" + }, + "link.item.label.Facebook": { + "message": "Facebook", + "description": "The label of footer link with label=Facebook linking to https://www.facebook.com/dhtmlx" + }, + "link.item.label.Twitter": { + "message": "Twitter", + "description": "The label of footer link with label=Twitter linking to https://twitter.com/dhtmlx" + }, + "link.item.label.Linkedin": { + "message": "Linkedin", + "description": "The label of footer link with label=Linkedin linking to https://www.linkedin.com/groups/3345009/" + }, + "link.item.label.About us": { + "message": "Über uns", + "description": "The label of footer link with label=About us linking to https://dhtmlx.com/docs/company.shtml" + }, + "link.item.label.Contact us": { + "message": "Kontakt", + "description": "The label of footer link with label=Contact us linking to https://dhtmlx.com/docs/contact.shtml" + }, + "link.item.label.Licensing": { + "message": "Lizenzierung", + "description": "The label of footer link with label=Licensing linking to https://dhtmlx.com/docs/products/dhtmlxPivot/#licensing" + } +} diff --git a/i18n/de/docusaurus-theme-classic/navbar.json b/i18n/de/docusaurus-theme-classic/navbar.json new file mode 100644 index 0000000..0747be8 --- /dev/null +++ b/i18n/de/docusaurus-theme-classic/navbar.json @@ -0,0 +1,26 @@ +{ + "title": { + "message": "JavaScript Pivot Dokumentation", + "description": "The title in the navbar" + }, + "logo.alt": { + "message": "DHTMLX JavaScript Pivot Logo", + "description": "The alt text of navbar logo" + }, + "item.label.Examples": { + "message": "Beispiele", + "description": "Navbar item with label Examples" + }, + "item.label.Forum": { + "message": "Forum", + "description": "Navbar item with label Forum" + }, + "item.label.Support": { + "message": "Support", + "description": "Navbar item with label Support" + }, + "item.label.Download": { + "message": "Download", + "description": "Navbar item with label Download" + } +} diff --git a/i18n/ko/code.json b/i18n/ko/code.json new file mode 100644 index 0000000..128780f --- /dev/null +++ b/i18n/ko/code.json @@ -0,0 +1,364 @@ +{ + "theme.ErrorPageContent.title": { + "message": "이 페이지가 중단되었습니다.", + "description": "The title of the fallback page when the page crashed" + }, + "theme.BackToTopButton.buttonAriaLabel": { + "message": "맨 위로 스크롤", + "description": "The ARIA label for the back to top button" + }, + "theme.blog.archive.title": { + "message": "보관함", + "description": "The page & hero title of the blog archive page" + }, + "theme.blog.archive.description": { + "message": "보관함", + "description": "The page & hero description of the blog archive page" + }, + "theme.blog.paginator.navAriaLabel": { + "message": "블로그 목록 페이지 내비게이션", + "description": "The ARIA label for the blog pagination" + }, + "theme.blog.paginator.newerEntries": { + "message": "새로운 항목", + "description": "The label used to navigate to the newer blog posts page (previous page)" + }, + "theme.blog.paginator.olderEntries": { + "message": "이전 항목", + "description": "The label used to navigate to the older blog posts page (next page)" + }, + "theme.blog.post.paginator.navAriaLabel": { + "message": "블로그 게시물 페이지 내비게이션", + "description": "The ARIA label for the blog posts pagination" + }, + "theme.blog.post.paginator.newerPost": { + "message": "새로운 게시물", + "description": "The blog post button label to navigate to the newer/previous post" + }, + "theme.blog.post.paginator.olderPost": { + "message": "이전 게시물", + "description": "The blog post button label to navigate to the older/next post" + }, + "theme.tags.tagsPageLink": { + "message": "모든 태그 보기", + "description": "The label of the link targeting the tag list page" + }, + "theme.colorToggle.ariaLabel.mode.system": { + "message": "시스템 모드", + "description": "The name for the system color mode" + }, + "theme.colorToggle.ariaLabel.mode.light": { + "message": "라이트 모드", + "description": "The name for the light color mode" + }, + "theme.colorToggle.ariaLabel.mode.dark": { + "message": "다크 모드", + "description": "The name for the dark color mode" + }, + "theme.colorToggle.ariaLabel": { + "message": "다크 모드와 라이트 모드 전환 (현재 {mode})", + "description": "The ARIA label for the color mode toggle" + }, + "theme.docs.breadcrumbs.navAriaLabel": { + "message": "경로 표시", + "description": "The ARIA label for the breadcrumbs" + }, + "theme.docs.DocCard.categoryDescription.plurals": { + "message": "{count}개 항목", + "description": "The default description for a category card in the generated index about how many items this category includes" + }, + "theme.docs.paginator.navAriaLabel": { + "message": "문서 페이지", + "description": "The ARIA label for the docs pagination" + }, + "theme.docs.paginator.previous": { + "message": "이전", + "description": "The label used to navigate to the previous doc" + }, + "theme.docs.paginator.next": { + "message": "다음", + "description": "The label used to navigate to the next doc" + }, + "theme.docs.tagDocListPageTitle.nDocsTagged": { + "message": "{count}개 문서 태그됨", + "description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.docs.tagDocListPageTitle": { + "message": "\"{tagName}\" 태그가 붙은 {nDocsTagged}", + "description": "The title of the page for a docs tag" + }, + "theme.docs.versionBadge.label": { + "message": "버전: {versionLabel}" + }, + "theme.docs.versions.unreleasedVersionLabel": { + "message": "{siteTitle} {versionLabel} 버전의 미출시 문서입니다.", + "description": "The label used to tell the user that he's browsing an unreleased doc version" + }, + "theme.docs.versions.unmaintainedVersionLabel": { + "message": "{siteTitle} {versionLabel} 버전의 문서이며 더 이상 적극적으로 유지 관리되지 않습니다.", + "description": "The label used to tell the user that he's browsing an unmaintained doc version" + }, + "theme.docs.versions.latestVersionSuggestionLabel": { + "message": "최신 문서는 {latestVersionLink} ({versionLabel})을 참조하세요.", + "description": "The label used to tell the user to check the latest version" + }, + "theme.docs.versions.latestVersionLinkLabel": { + "message": "최신 버전", + "description": "The label used for the latest version suggestion link label" + }, + "theme.common.editThisPage": { + "message": "이 페이지 편집하기", + "description": "The link label to edit the current page" + }, + "theme.common.headingLinkTitle": { + "message": "{heading}로 직접 연결", + "description": "Title for link to heading" + }, + "theme.lastUpdated.atDate": { + "message": " {date}에", + "description": "The words used to describe on which date a page has been last updated" + }, + "theme.lastUpdated.byUser": { + "message": " {user}에 의해", + "description": "The words used to describe by who the page has been last updated" + }, + "theme.lastUpdated.lastUpdatedAtBy": { + "message": "마지막 업데이트{atDate}{byUser}", + "description": "The sentence used to display when a page has been last updated, and by who" + }, + "theme.navbar.mobileVersionsDropdown.label": { + "message": "버전", + "description": "The label for the navbar versions dropdown on mobile view" + }, + "theme.NotFound.title": { + "message": "페이지를 찾을 수 없습니다", + "description": "The title of the 404 page" + }, + "theme.tags.tagsListLabel": { + "message": "태그:", + "description": "The label alongside a tag list" + }, + "theme.admonition.caution": { + "message": "주의", + "description": "The default label used for the Caution admonition (:::caution)" + }, + "theme.admonition.danger": { + "message": "위험", + "description": "The default label used for the Danger admonition (:::danger)" + }, + "theme.admonition.info": { + "message": "정보", + "description": "The default label used for the Info admonition (:::info)" + }, + "theme.admonition.note": { + "message": "노트", + "description": "The default label used for the Note admonition (:::note)" + }, + "theme.admonition.tip": { + "message": "팁", + "description": "The default label used for the Tip admonition (:::tip)" + }, + "theme.admonition.warning": { + "message": "경고", + "description": "The default label used for the Warning admonition (:::warning)" + }, + "theme.AnnouncementBar.closeButtonAriaLabel": { + "message": "닫기", + "description": "The ARIA label for close button of announcement bar" + }, + "theme.blog.sidebar.navAriaLabel": { + "message": "블로그 최근 게시물 내비게이션", + "description": "The ARIA label for recent posts in the blog sidebar" + }, + "theme.DocSidebarItem.expandCategoryAriaLabel": { + "message": "사이드바 카테고리 '{label}' 확장", + "description": "The ARIA label to expand the sidebar category" + }, + "theme.DocSidebarItem.collapseCategoryAriaLabel": { + "message": "사이드바 카테고리 '{label}' 축소", + "description": "The ARIA label to collapse the sidebar category" + }, + "theme.IconExternalLink.ariaLabel": { + "message": "(새 탭에서 열림)", + "description": "The ARIA label for the external link icon" + }, + "theme.NavBar.navAriaLabel": { + "message": "메인", + "description": "The ARIA label for the main navigation" + }, + "theme.navbar.mobileLanguageDropdown.label": { + "message": "언어", + "description": "The label for the mobile language switcher dropdown" + }, + "theme.NotFound.p1": { + "message": "찾으려던 내용을 찾을 수 없습니다.", + "description": "The first paragraph of the 404 page" + }, + "theme.NotFound.p2": { + "message": "원본 URL에 연결된 사이트 소유자에게 연락하여 링크가 끊어졌음을 알려주세요.", + "description": "The 2nd paragraph of the 404 page" + }, + "theme.TOCCollapsible.toggleButtonLabel": { + "message": "이 페이지 내", + "description": "The label used by the button on the collapsible TOC component" + }, + "theme.blog.post.readMore": { + "message": "더 읽기", + "description": "The label used in blog post item excerpts to link to full blog posts" + }, + "theme.blog.post.readMoreLabel": { + "message": "{title}에 대해 더 읽기", + "description": "The ARIA label for the link to full blog posts from excerpts" + }, + "theme.blog.post.readingTime.plurals": { + "message": "{readingTime}분 읽기", + "description": "Pluralized label for \"{readingTime} min read\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.CodeBlock.copy": { + "message": "복사", + "description": "The copy button label on code blocks" + }, + "theme.CodeBlock.copied": { + "message": "복사됨", + "description": "The copied button label on code blocks" + }, + "theme.CodeBlock.copyButtonAriaLabel": { + "message": "코드를 클립보드에 복사", + "description": "The ARIA label for copy code blocks button" + }, + "theme.CodeBlock.wordWrapToggle": { + "message": "단어 줄바꿈 전환", + "description": "The title attribute for toggle word wrapping button of code block lines" + }, + "theme.docs.breadcrumbs.home": { + "message": "홈 페이지", + "description": "The ARIA label for the home page in the breadcrumbs" + }, + "theme.docs.sidebar.collapseButtonTitle": { + "message": "사이드바 축소", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.collapseButtonAriaLabel": { + "message": "사이드바 축소", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.navAriaLabel": { + "message": "문서 사이드바", + "description": "The ARIA label for the sidebar navigation" + }, + "theme.docs.sidebar.closeSidebarButtonAriaLabel": { + "message": "내비게이션 바 닫기", + "description": "The ARIA label for close button of mobile sidebar" + }, + "theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": { + "message": "← 메인 메뉴로 돌아가기", + "description": "The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)" + }, + "theme.docs.sidebar.toggleSidebarButtonAriaLabel": { + "message": "내비게이션 바 전환", + "description": "The ARIA label for hamburger menu button of mobile navigation" + }, + "theme.navbar.mobileDropdown.collapseButton.expandAriaLabel": { + "message": "드롭다운 펼치기", + "description": "The ARIA label of the button to expand the mobile dropdown navbar item" + }, + "theme.navbar.mobileDropdown.collapseButton.collapseAriaLabel": { + "message": "드롭다운 접기", + "description": "The ARIA label of the button to collapse the mobile dropdown navbar item" + }, + "theme.docs.sidebar.expandButtonTitle": { + "message": "사이드바 확장", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.docs.sidebar.expandButtonAriaLabel": { + "message": "사이드바 확장", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.SearchBar.noResultsText": { + "message": "결과 없음" + }, + "theme.SearchBar.seeAllOutsideContext": { + "message": "\"{context}\" 외부의 모든 결과 보기" + }, + "theme.SearchBar.searchInContext": { + "message": "\"{context}\" 내의 모든 결과 보기" + }, + "theme.SearchBar.seeAll": { + "message": "모든 {count}개 결과 보기" + }, + "theme.SearchBar.label": { + "message": "검색", + "description": "The ARIA label and placeholder for search button" + }, + "theme.SearchPage.existingResultsTitle": { + "message": "\"{query}\" 검색 결과", + "description": "The search page title for non-empty query" + }, + "theme.SearchPage.emptyResultsTitle": { + "message": "문서 검색", + "description": "The search page title for empty query" + }, + "theme.SearchPage.searchContext.everywhere": { + "message": "전체" + }, + "theme.SearchPage.documentsFound.plurals": { + "message": "{count}개 문서 발견", + "description": "Pluralized label for \"{count} documents found\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.SearchPage.noResultsText": { + "message": "결과를 찾을 수 없습니다", + "description": "The paragraph for empty search result" + }, + "theme.blog.post.plurals": { + "message": "{count}개 게시물", + "description": "Pluralized label for \"{count} posts\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.blog.tagTitle": { + "message": "\"{tagName}\" 태그가 붙은 {nPosts}개 게시물", + "description": "The title of the page for a blog tag" + }, + "theme.blog.author.pageTitle": { + "message": "{authorName} - {nPosts}개 게시물", + "description": "The title of the page for a blog author" + }, + "theme.blog.authorsList.pageTitle": { + "message": "저자", + "description": "The title of the authors page" + }, + "theme.blog.authorsList.viewAll": { + "message": "모든 저자 보기", + "description": "The label of the link targeting the blog authors page" + }, + "theme.blog.author.noPosts": { + "message": "이 저자는 아직 게시물을 작성하지 않았습니다.", + "description": "The text for authors with 0 blog post" + }, + "theme.contentVisibility.unlistedBanner.title": { + "message": "비공개 페이지", + "description": "The unlisted content banner title" + }, + "theme.contentVisibility.unlistedBanner.message": { + "message": "이 페이지는 비공개입니다. 검색 엔진에 인덱싱되지 않으며 직접 링크를 가진 사용자만 접근할 수 있습니다.", + "description": "The unlisted content banner message" + }, + "theme.contentVisibility.draftBanner.title": { + "message": "초안 페이지", + "description": "The draft content banner title" + }, + "theme.contentVisibility.draftBanner.message": { + "message": "이 페이지는 초안입니다. 개발 환경에서만 볼 수 있으며 프로덕션 빌드에서는 제외됩니다.", + "description": "The draft content banner message" + }, + "theme.ErrorPageContent.tryAgain": { + "message": "다시 시도", + "description": "The label of the button to try again rendering when the React error boundary captures an error" + }, + "theme.common.skipToMainContent": { + "message": "주요 콘텐츠로 건너뛰기", + "description": "The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation" + }, + "theme.tags.tagsPageTitle": { + "message": "태그", + "description": "The title of the tag list page" + } +} diff --git a/i18n/ko/docusaurus-plugin-content-blog/options.json b/i18n/ko/docusaurus-plugin-content-blog/options.json new file mode 100644 index 0000000..3b7edef --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-blog/options.json @@ -0,0 +1,14 @@ +{ + "title": { + "message": "블로그", + "description": "The title for the blog used in SEO" + }, + "description": { + "message": "블로그", + "description": "The description for the blog used in SEO" + }, + "sidebar.title": { + "message": "최근 게시물", + "description": "The label for the left sidebar" + } +} diff --git a/i18n/ko/docusaurus-plugin-content-docs/current.json b/i18n/ko/docusaurus-plugin-content-docs/current.json new file mode 100644 index 0000000..7b76967 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current.json @@ -0,0 +1,70 @@ +{ + "version.label": { + "message": "다음", + "description": "The label for version current" + }, + "sidebar.docs.category.What's new and migration": { + "message": "새로운 기능 및 마이그레이션", + "description": "The label for category 'What's new and migration' in sidebar 'docs'" + }, + "sidebar.docs.category.What's new and migration.link.generated-index.title": { + "message": "새로운 기능 및 마이그레이션", + "description": "The generated-index page title for category 'What's new and migration' in sidebar 'docs'" + }, + "sidebar.docs.category.API": { + "message": "API", + "description": "The label for category 'API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot methods": { + "message": "Pivot 메서드", + "description": "The label for category 'Pivot methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API": { + "message": "Pivot 내부 API", + "description": "The label for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API.link.generated-index.title": { + "message": "내부 API 개요", + "description": "The generated-index page title for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Event Bus methods": { + "message": "이벤트 버스 메서드", + "description": "The label for category 'Event Bus methods' in sidebar 'docs'" + }, + "sidebar.docs.category.State methods": { + "message": "상태 메서드", + "description": "The label for category 'State methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot events": { + "message": "Pivot 이벤트", + "description": "The label for category 'Pivot events' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot properties": { + "message": "Pivot 속성", + "description": "The label for category 'Pivot properties' in sidebar 'docs'" + }, + "sidebar.docs.category.Table events": { + "message": "Table 이벤트", + "description": "The label for category 'Table events' in sidebar 'docs'" + }, + "sidebar.docs.category.Helpers": { + "message": "헬퍼", + "description": "The label for category 'Helpers' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks": { + "message": "프레임워크 통합", + "description": "The label for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks.link.generated-index.title": { + "message": "프레임워크 통합", + "description": "The generated-index page title for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides": { + "message": "가이드", + "description": "The label for category 'Guides' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides.link.generated-index.title": { + "message": "가이드", + "description": "The generated-index page title for category 'Guides' in sidebar 'docs'" + } +} diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/.sync b/i18n/ko/docusaurus-plugin-content-docs/current/.sync new file mode 100644 index 0000000..ef543cf --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/.sync @@ -0,0 +1 @@ +05469ebe9355e2393701b28c3c5126da9be5d566 diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md new file mode 100644 index 0000000..c3d15c6 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md @@ -0,0 +1,82 @@ +--- +sidebar_label: columnShape +title: columnShape Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 columnShape config에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# columnShape + +### 설명 {#description} + +@short: 선택 사항. Pivot 열의 외관과 동작을 구성합니다 + +### 사용법 {#usage} + +~~~jsx +columnShape?: { + sort?: boolean, + width?: { + [field: string]: number + }, + autoWidth?: { + columns: { + [field: string]: boolean + }, + auto?: boolean | "header" | "data", + maxRows?: number, + firstOnly?: boolean + } +}; +~~~ + +### 매개변수 {#parameters} + +- `sort` - (선택 사항) **true**(기본값)이면 열 헤더 클릭 시 UI에서 정렬이 활성화됩니다. **false**이면 정렬이 비활성화됩니다 +- `width` - (선택 사항) 열의 너비를 정의합니다. 각 키가 필드 id이고 값이 픽셀 단위의 열 너비인 객체입니다 +- `autoWidth` - (선택 사항) 열 너비를 자동으로 계산하는 방법을 정의하는 객체입니다. 기본 구성은 20개의 행을 사용하며, 헤더와 데이터를 기반으로 너비를 계산하고 각 필드는 한 번만 분석됩니다. 객체의 매개변수는 다음과 같습니다: + - `columns` - (필수) 각 키가 필드 id이고 boolean 값이 해당 열 너비를 자동으로 계산할지 여부를 정의하는 객체입니다 + - `auto` - (선택 사항) **header**로 설정하면 헤더 텍스트에 맞게 너비를 조정하고, **data**로 설정하면 콘텐츠가 가장 넓은 셀에 맞게 너비를 조정하며, **true**로 설정하면 헤더와 셀의 콘텐츠 모두에 맞게 너비를 조정합니다. + autowidth가 **false**로 설정된 경우, `width` 값이 설정되거나 [`tableShape`](api/config/tableshape-property.md) 속성의 `columnWidth` 값이 적용됩니다. + - `maxRows` - (선택 사항) autoWidth 계산 시 처리할 행의 수입니다 + - `firstOnly` - (선택 사항) **true**(기본값)로 설정하면 동일한 데이터의 각 필드는 열 너비 계산을 위해 한 번만 분석됩니다. 동일한 데이터를 기반으로 여러 열이 있는 경우(예: *count* 연산의 *oil* 필드와 *sum* 연산의 *oil* 필드), 첫 번째 열의 데이터만 분석되고 나머지는 해당 너비를 상속합니다 + +## 예제 {#example} + +~~~jsx {18-31} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + autoWidth: { + // 이 필드들의 열 너비를 계산합니다 + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + auto: true, + // 모든 필드를 분석합니다 + firstOnly: false + } + } +}); +~~~ + +**관련 샘플**: +- [Pivot 2. 자동 너비 - 콘텐츠에 맞게 열 크기 조정](https://snippet.dhtmlx.com/tn1yw14m) +- [Pivot 2. 열 너비 설정](https://snippet.dhtmlx.com/ceu34kkn) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/config-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/config-property.md new file mode 100644 index 0000000..2f15c85 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/config-property.md @@ -0,0 +1,146 @@ +--- +sidebar_label: config +title: config Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 config 설정에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# config + +### 설명 {#description} + +@short: 선택 사항. Pivot 테이블의 구조와 데이터 집계 방식을 정의합니다 + +### 사용법 {#usage} + +~~~jsx +config?: { + rows?: string | {field: string, method?: string}[], + columns?: string | {field: string, method?: string}[], + values?: string | {field: string, method?: string}[], + filters?: {} +}; +~~~ + +### 매개변수 {#parameters} + +`config` 매개변수는 행과 열에 적용할 필드 및 행/열에 대한 추가 데이터 집계 방법을 정의하는 데 사용됩니다. + +- `rows` - (선택 사항) Pivot 테이블의 행을 정의합니다. 기본값은 빈 배열입니다. 단일 필드 ID를 나타내는 문자열이나 필드 ID와 데이터 추출 방법을 포함하는 객체를 사용할 수 있습니다. 객체의 매개변수는 다음과 같습니다: + - `field` - (필수) 필드의 ID + - `method` - (선택 사항) 해당 필드에서 데이터 집계에 사용할 방법을 정의합니다. 시간 기반 데이터 필드에는 기본적으로 "year", "quarter", "month", "week", "day", "hour", "minute" 방법이 제공되며, 이를 통해 데이터를 그룹화할 수 있습니다. 또한 임의의 데이터 유형 필드에 사용자 정의 방법의 이름을 추가할 수 있습니다([`predicates` 참고](api/config/predicates-property.md)). +- `columns` - (선택 사항) Pivot 테이블의 열을 정의합니다. 기본값은 빈 배열입니다. 단일 필드 ID나 필드 ID와 데이터 추출 방법을 포함하는 객체를 사용할 수 있습니다. 객체의 매개변수는 다음과 같습니다: + - `field` - (필수) 필드의 ID + - `method` - (선택 사항) 데이터 처리에 사용할 방법을 정의합니다(시간 기반 데이터 필드의 경우). + 기본적으로 시간 기반 필드(**date** 타입)에는 "year", "quarter", "month", "week", "day", "hour", "minute" 값의 방법이 제공됩니다. 또한 임의의 데이터 유형 필드에 사용자 정의 방법의 이름을 추가할 수 있습니다([`predicates` 참고](api/config/predicates-property.md)). +- `values` - (선택 사항) Pivot 테이블 셀의 데이터 집계를 정의합니다. 기본값은 빈 배열입니다. 각 요소는 데이터 필드 ID와 집계 방법을 나타내는 문자열이거나, 필드 ID와 데이터 집계 방법을 포함하는 객체일 수 있습니다. 객체의 매개변수는 다음과 같습니다: + - `field` - (필수) 필드의 ID + - `method` - (필수) 데이터 추출에 사용할 방법을 정의합니다. 방법의 유형 및 설명은 [방법 적용하기](guides/working-with-data.md#default-methods)를 참고하세요. + +
+ +values 정의 옵션 + +`values`는 동일하게 유효한 두 가지 방법 중 하나로 정의할 수 있습니다: +- 옵션 1: 필드 ID를 나타내는 문자열 +- 옵션 2: 필드 ID와 데이터 집계 방법을 포함하는 객체 + +### 예제 {#example} + +~~~jsx +values: [ + "sum(sales)", // 옵션 1 + { field: "sales", method: "sum" }, // 옵션 2 +] +~~~ + +
+ +- `filters` - (선택 사항) 테이블에서 데이터를 필터링하는 방식을 정의합니다. 필드 ID와 필터링 규칙을 포함하는 객체입니다. 기본값은 빈 객체입니다. 객체의 매개변수는 다음과 같습니다: + - `field` - (선택 사항) 필드의 ID 또는 필터링 기준이 있는 ID 배열을 키로 사용하는 필터: + - `equal` - (선택 사항) 숫자, 문자열, Date 값을 허용합니다 + - `notEqual` - (선택 사항) 숫자, 문자열, Date 값을 허용합니다 + - `greater` - (선택 사항) 숫자 및 Date 값을 허용합니다 + - `greaterOrEqual` - (선택 사항) 숫자 및 Date 값을 허용합니다 + - `less` - (선택 사항) 숫자 및 Date 값을 허용합니다 + - `lessOrEqual` - 숫자 및 Date 값을 허용합니다 + - `between` - 다음 매개변수를 포함하는 객체: + - `start` - Date + - `end` - Date + - `notBetween` - 다음 매개변수를 포함하는 객체: + - `start` - Date + - `end` - Date + - `contains` - 문자열 값과 숫자를 허용합니다 + - `notContains` - 문자열 값과 숫자를 허용합니다 + - `beginsWith` - 문자열 값과 숫자를 허용합니다 + - `notBeginsWith` - 문자열 값과 숫자를 허용합니다 + - `endsWith` - 문자열 값과 숫자를 허용합니다 + - `notEndsWith` - 문자열 값과 숫자를 허용합니다 + - `includes` - (선택 사항) 이미 필터링된 값 중에서 표시할 값의 배열. 텍스트 및 날짜 값에 사용 가능합니다 + +:::info +config가 Pivot에 의해 처리되면 해당 속성에 추가 데이터가 포함됩니다. [`api.getState()`](api/internal/getstate-method.md) 메서드를 통해 config 상태를 반환하려고 하면 전체 객체는 다음과 같이 표시됩니다: + +~~~jsx +interface IParsedField { + id: string, + field: string, + method: string | null, + area: 'rows'|'columns'|'values', + base?: string, + label: string, + type: 'number'|'date'|'text' +} + +interface IParsedConfig { + rows: IParsedField[], + columns: IParsedField[], + values: IParsedField[], + filters: { + [field: string]: number | string | [] | + { [operation: string]: number | string | [] | { start:Date, end: Date} } + } +} +~~~ + +매개변수: + +- `id` - 처리된 필드의 고유 ID +- `field` - 필드 이름 +- `method` - 집계에 사용되는 작업 이름. rows 및 columns의 경우 method는 선택 사항이며, 제공된 경우 predicate로 작동하여 집계 전에 필드 데이터를 사전 처리하는 방식을 정의합니다. values의 경우 method는 필수 매개변수입니다. +- `area` - 필드가 추가되는 영역 +- `base` - predicate가 있는 필드의 columns 및 rows에서 사용됩니다. 원본 필드 이름을 정의하며, 필드 이름은 "field_by_predicate" 패턴에 따라 구성됩니다. +- `label` - 텍스트 레이블 +- `type` - 데이터 유형 +::: + +### 예제 {#example} + +~~~jsx {4-26} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // 다른 필드("title")에 대한 필터 + contains: "A" + } + } + } +}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md new file mode 100644 index 0000000..a4477fc --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md @@ -0,0 +1,58 @@ +--- +sidebar_label: configPanel +title: configPanel 설정 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 configPanel 설정에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 사용해 보고, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# configPanel + +### 설명 {#description} + +@short: 선택 사항. UI에서 구성 패널의 표시 여부를 제어합니다 + +UI에서 **Hide Settings** 버튼을 클릭하면 패널이 숨겨지거나 표시됩니다. + +### 사용법 {#usage} + +~~~jsx +configPanel?: boolean; +~~~ + +### 매개변수 {#parameters} + +이 속성은 **true** 또는 **false**로 설정할 수 있습니다: + +- `true` - 기본값, 구성 패널을 표시합니다 +- `false` - 구성 패널을 숨깁니다 + +## 예제 {#example} + +~~~jsx {5} +// 초기화 시 구성 패널이 숨겨집니다 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + configPanel: false, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +**관련 샘플**: [Pivot 2.0: 구성 패널 표시 여부 전환](https://snippet.dhtmlx.com/1xq1x5bo) + +**관련 문서**: +- [`show-config-panel` 이벤트](api/events/show-config-panel-event.md) +- [`showConfigPanel()` 메서드](api/methods/showconfigpanel-method.md) +- [구성 패널 표시 여부 제어](guides/configuration.md#controlling-visibility-of-configuration-panel) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/data-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/data-property.md new file mode 100644 index 0000000..40774de --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/data-property.md @@ -0,0 +1,129 @@ +--- +sidebar_label: data +title: data Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 data config에 대해 알아볼 수 있습니다. 개발자 가이드 및 API 참조를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. 또한 DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# data + +### 설명 {#description} + +@short: 선택 사항. Pivot 테이블의 데이터를 포함하는 객체 배열 + +### 사용법 {#usage} + +~~~jsx +data?: []; +~~~ + +### 매개변수 {#parameters} + +`data` 배열의 각 객체는 하나의 행을 나타냅니다. 기본값은 빈 배열입니다. +`data` 속성의 직접적인 하위 속성은 없습니다. 그러나 배열의 각 객체는 Pivot 테이블의 차원과 값을 나타내는 임의 개수의 속성을 가질 수 있습니다. + +`data` 배열 예시: + +~~~jsx +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + { + name: "Argentina", + year: 2017, + continent: "South America", + form: "Republic", + gdp: 212.507, + oil: 1.732, + balance: 7.167, + when: new Date("1/15/2017") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 260.071, + oil: 2.845, + balance: 6.728, + when: new Date("6/16/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 324.405, + oil: 4.333, + balance: 5.99, + when: new Date("2/20/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 305.763, + oil: 2.626, + balance: 7.544, + when: new Date("8/17/2014") + }, + //다른 데이터 +]; +~~~ + +### 예제 {#example} + +~~~jsx {3-29} +const table = new pivot.Pivot("#root", { + fields, + data: [ + { + rank: 1, + title: "Shingeki no Kyojin: The Final Season - Kanketsu-hen", + popularity: 609, + genre: "Action", + studio: "MAPPA", + type: "Special", + episodes: 2, + duration: 61, + members: 347875, + score: 9.17, + }, + { + rank: 2, + title: "Fullmetal Alchemist: Brotherhood", + popularity: 3, + genre: "Action", + studio: "Bones", + type: "TV", + episodes: 64, + duration: 24, + members: 3109951, + score: 9.11 + }, + //다른 데이터 객체 + ], + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/fields-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/fields-property.md new file mode 100644 index 0000000..65df258 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/fields-property.md @@ -0,0 +1,112 @@ +--- +sidebar_label: fields +title: fields Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 fields 설정에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# fields + +### 설명 {#description} + +@short: 선택 사항. Pivot 테이블의 필드를 정의하는 객체 배열 + +`fields` 속성은 구성 객체에서 위젯이 수신하는 데이터 필드의 타입을 해석하는 방법을 제어하고, 필드의 정렬 순서를 정의할 수 있게 합니다. + +### 사용법 {#usage} + +~~~jsx +fields?: [{ + id: string, + label?: string, + type: "number" | "date" | "text", + sort?: "asc" | "desc" | ((a: any, b: any) => number), + format?: string | boolean | numberFormatOptions{} +}]; +~~~ + +### 매개변수 {#parameters} + +기본적으로 이 속성이 설정되지 않은 경우, 위젯은 수신된 데이터를 자동으로 분석하고 그에 따라 `fields` 객체를 채웁니다. + +`fields` 배열의 각 객체에는 다음 속성이 있어야 합니다: + +- `id` - (필수) 필드의 ID +- `label` - (선택 사항) GUI에 표시될 필드 레이블 +- `type` - (필수) 필드의 데이터 타입 ("number", "date", 또는 "text") +- `sort` - (선택 사항) 필드의 기본 정렬 순서를 정의합니다. "asc", "desc" 또는 사용자 정의 정렬 함수를 허용합니다 +- `format` - (선택 사항) 필드에서 숫자와 날짜의 형식을 사용자 정의할 수 있습니다; 형식은 [내보내기](guides/exporting-data.md) 중에도 적용됩니다 + - `string` - (선택 사항) 날짜 형식 (기본적으로 Pivot은 로케일의 `dateFormat`을 사용합니다) + - `boolean` - (선택 사항) **false**로 설정하면 숫자가 형식 없이 그대로 표시됩니다 + - `numberFormatOptions` - (선택 사항) 숫자 필드 형식 지정을 위한 옵션 객체; 기본적으로 숫자는 최대 3자리 소수 자릿수로 표시되고 정수 부분에 그룹 구분이 적용됩니다. + - `minimumIntegerDigits`(number) - (선택 사항) 최소 정수 자릿수 (예: 값이 2로 설정되면 숫자 1이 "01"로 표시됨); 기본값은 1; + - `minimumFractionDigits`(number) - (선택 사항) 사용할 최소 소수 자릿수 (예: 값이 2로 설정되면 숫자 10.5가 "10.50"으로 표시됨); 기본값은 0; + - `maximumFractionDigits`(number) - (선택 사항) 사용할 최대 소수 자릿수 (예: 값이 2로 설정되면 숫자 10.3333...이 "10.33"으로 표시됨); 기본값은 3; + 자릿수 옵션에 대한 자세한 내용은 [자릿수 옵션](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumintegerdigits)을 참조하세요 + - `prefix` (string) - (선택 사항) 통화 기호 등의 추가 기호를 위해 숫자 앞에 붙는 문자열 + - `suffix` (string) - (선택 사항) 통화 기호 등의 추가 기호를 위해 숫자 뒤에 붙는 문자열 + +:::info +[`tableShape`](api/config/tableshape-property.md) 속성을 통해 템플릿이 적용되면 `format` 설정이 재정의됩니다. +::: + +### 예제 {#example} + +~~~jsx {2-34} +const table = new pivot.Pivot("#root", { + fields: [ + { + id: "rank", + label: "Rank", + type: "number" + }, + { + id: "title", + label: "Title", + type: "text" + }, + { + id: "genre", + label: "Genre", + type: "text" + }, + { + id: "studio", + label: "Studio", + type: "text" + }, + { + id: "type", + label: "Type", + type: "text" + }, + { + id: "score", + label: "Score", + type: "number" + }, + //다른 필드들 + ], + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +**관련 문서**: + +- [숫자 형식 지정](guides/localization.md#number-formatting) +- [필드에 형식 적용하기](guides/working-with-data.md#applying-formats-to-fields) + +**관련 샘플**: [Pivot 2. 필드 형식 정의하기](https://snippet.dhtmlx.com/77nc4j8v) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/headershape-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/headershape-property.md new file mode 100644 index 0000000..6bf4656 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/headershape-property.md @@ -0,0 +1,83 @@ +--- +sidebar_label: headerShape +title: headerShape Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 headerShape config에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판을 다운로드하실 수 있습니다. +--- + +# headerShape + +### 설명 {#description} + +@short: 선택 사항입니다. Pivot 테이블 헤더의 외관과 동작을 구성합니다 + +### 사용법 {#usage} + +~~~jsx +headerShape?: { + collapsible?: boolean, + vertical?: boolean, + template?: (label: string, field: string, subLabel?: string) => string, + cellStyle?: ( + field: string, + value: any, + area: "rows"|"columns"|"values", + method?: string, + isTotal?: boolean) + => string, +}; +~~~ + +### 매개변수 {#parameters} + +- `collapsible` - (선택 사항) **true**로 설정하면 테이블의 차원 그룹을 접을 수 있습니다. 기본값은 **false**입니다 +- `vertical` - (선택 사항) **true**로 설정하면 모든 헤더의 텍스트 방향이 가로에서 세로로 변경됩니다. 기본값은 **false**입니다 +- `cellStyle` - (선택 사항) 헤더 셀에 사용자 정의 스타일을 적용하는 함수입니다. 이 함수는 css 클래스 이름을 반환하며 다음 매개변수를 받습니다: + - `field` (string) - (필수) 셀이 해당하는 필드 이름을 나타내는 문자열입니다. 트리 열의 헤더인 경우 field는 ""입니다 + - `value` (string | number | date) - (필수) 셀의 값입니다 + - `area` - (필수) 셀이 위치한 테이블 영역을 나타내는 문자열입니다("rows", "columns" 또는 "values" 영역) + - `method` (string) - (선택 사항) "values" 영역의 필드에 대해 수행되는 연산(예: "sum", "count" 등)이나 "columns" 영역의 필드에 설정된 predicate 이름을 나타낼 수 있는 문자열입니다 + - `isTotal` - (선택 사항) 셀이 합계 열에 속하는지 여부를 정의합니다 +- `template` - (선택 사항) 헤더의 텍스트 형식을 정의합니다. 기본적으로 행으로 적용된 필드에는 `label` 매개변수 값이 표시되고, 값으로 적용된 필드에는 label과 method가 함께 표시됩니다(예: *Oil(count)*). 이 함수는 필드 id, label, 그리고 method 또는 predicate id(있는 경우)를 받아 처리된 값을 반환합니다. 기본 template은 다음과 같습니다: +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +## 예제 {#example} + +아래 예제에서 **values** 필드의 헤더는 label과 method 이름(subLabel)을 표시하고 결과를 소문자로 변환합니다(예: *profit (sum)*): + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // 헤더 텍스트의 사용자 정의 template + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // other values + ], + }, + fields, +}); +~~~ + +**관련 샘플**: +- [Pivot 2. 그리드 헤더의 세로 텍스트 방향](https://snippet.dhtmlx.com/4qroi8ka) +- [Pivot 2. 접을 수 있는 열](https://snippet.dhtmlx.com/pt2ljmcm) +- [Pivot 2. 테이블 및 헤더 셀에 사용자 정의 CSS 추가](https://snippet.dhtmlx.com/nfdcs4i2) + +**관련 문서**: +- [구성](guides/configuration.md) +- [셀 스타일](guides/stylization.md#cell-style) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/limits-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/limits-property.md new file mode 100644 index 0000000..84d5543 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/limits-property.md @@ -0,0 +1,61 @@ +--- +sidebar_label: limits +title: limits Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 limits config에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 사용해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드하실 수 있습니다. +--- + +# limits + +### 설명 {#description} + +@short: 선택 사항입니다. 최종 데이터셋의 행과 열 수에 대한 최대 제한을 정의합니다. + +[데이터 제한](guides/working-with-data.md#limiting-loaded-data)도 함께 참고하시기 바랍니다. + +### 사용법 {#usage} + +~~~jsx +limits?: { + rows?: number, + columns?: number, + raws?: number +}; +~~~ + +### 파라미터 {#parameters} + +각 파라미터는 데이터 렌더링을 중단할 시점을 정의합니다: + +- `rows` - (선택 사항) 최종 데이터셋의 최대 행 수를 설정합니다. 기본값은 10000입니다. +- `columns` - (선택 사항) 최종 데이터셋의 최대 열 수를 설정합니다. 기본값은 5000입니다. +- `raws` - (선택 사항) 데이터 그룹화 전 소스 데이터의 최대 행 수입니다(집계에 사용되는 원시 데이터 레코드). 기본값은 무한대입니다. + +:::note +Limits는 대용량 데이터셋에 사용됩니다. Limits 값은 근사치이며 행과 열의 정확한 값을 나타내지 않습니다. +::: + +## 예제 {#example} + +~~~jsx {18} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + ], + }, + limits:{ rows: 25, columns: 4 } +}); +~~~ + +**관련 샘플**: [Pivot 2. 데이터 제한](https://snippet.dhtmlx.com/7ryns8oe) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/locale-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/locale-property.md new file mode 100644 index 0000000..877a58c --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/locale-property.md @@ -0,0 +1,51 @@ +--- +sidebar_label: locale +title: locale 설정 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 locale 설정에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 실행해 보세요. 또한 DHTMLX Pivot 30일 무료 평가판을 다운로드할 수 있습니다. +--- + +# locale + +### 설명 {#description} + +@short: 선택 사항. Pivot의 사용자 정의 로케일 객체 + +### 사용법 {#usage} + +~~~jsx +locale?: object; +~~~ + +### 기본 설정 {#default-config} + +기본적으로 Pivot은 [영어](guides/localization.md#default-locale) 로케일을 사용합니다. 사용자 정의 로케일로 변경할 수도 있습니다. + +:::tip +현재 로케일을 동적으로 변경하려면 Pivot의 [`setLocale()`](api/methods/setlocale-method.md) 메서드를 사용할 수 있습니다. +::: + +### 예제 {#example} + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + + locale: pivot.locales.cn, // 처음에 "cn" 로케일이 설정됩니다 + // 기타 매개변수 +}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/methods-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/methods-property.md new file mode 100644 index 0000000..8e38088 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/methods-property.md @@ -0,0 +1,163 @@ +--- +sidebar_label: methods +title: methods Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 methods 설정에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# methods + +### 설명 {#description} + +@short: 선택 사항. 데이터 집계를 위한 사용자 정의 수학 메서드를 정의합니다 + +### 사용법 {#usage} + +~~~jsx +methods?: { + [method: string]: { + type?: 'number' | 'date' | 'text' | [], + label?: string, + handler?: (values: number[]) => number, + branchMode?: "raw"|"result", + branchMath?: string + } +}; +~~~ + +### 파라미터 {#parameters} + +각 메서드는 키-값 쌍으로 표현되며, `method`는 메서드의 이름이고 값은 해당 메서드의 동작을 설명하는 객체입니다. 각 객체에는 다음과 같은 파라미터가 있습니다: + +- `handler` - (사용자 정의 메서드에 필수) 숫자 배열에서 집계 값을 계산하는 함수로, 값 배열을 입력으로 받아 단일 값을 반환합니다 +- `type` - (선택 사항) 이 메서드가 적용되는 데이터 타입으로, "number", "date", "text" 또는 이들의 배열로 지정할 수 있습니다 +- `label` - (선택 사항) GUI에 표시될 메서드 레이블 +- `branchMode` - (선택 사항) 트리 테이블에서 합계 값 계산 방식을 정의합니다. `raw`로 설정하면 모든 원시 데이터를 기반으로 계산하고, `result`(기본값)는 트리 모드에서 이미 처리된 데이터를 기반으로 계산합니다 +- `branchMath` - (선택 사항) 트리 모드에서 합계 값을 계산할 메서드 이름으로, 기본적으로 메서드 이름과 동일합니다 ("max" 메서드의 경우 branchMath도 "max") + +기본적으로 `methods` 속성은 빈 객체 {}이며, 사용자 정의 메서드가 정의되지 않음을 의미합니다. methods 객체에 정의할 수 있는 하위 속성의 수에는 제한이 없습니다. + +미리 정의된 메서드: + +~~~jsx +defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +각 메서드의 정의는 여기에서 확인할 수 있습니다: [메서드 적용하기](guides/working-with-data.md#default-methods) + +## 예제 {#example} + +아래 예제는 날짜 타입에 대해 고유 값 개수와 평균 값을 계산하는 방법을 보여줍니다. **countUnique** 함수는 숫자(값) 배열을 입력으로 받아 **reduce** 메서드를 사용하여 정확한 고유 값의 개수를 계산합니다. **countunique_date** 하위 속성에는 날짜 값 배열에서 고유 값을 가져오는 함수가 포함된 handler가 있습니다. **average_date** 하위 속성에는 날짜 값 배열에서 평균 값을 계산하는 handler가 있습니다. + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique" + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// "count" 및 "unique count" 결과에 정수를 표시합니다 +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// 날짜 문자열을 Date로 변환합니다 +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +**관련 샘플**: [Pivot 2. 사용자 정의 수학 메서드](https://snippet.dhtmlx.com/lv90d8q2) + +**관련 문서**: [수학 메서드 적용하기](guides/working-with-data.md#applying-maths-methods) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/predicates-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/predicates-property.md new file mode 100644 index 0000000..09a8ce8 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/predicates-property.md @@ -0,0 +1,117 @@ +--- +sidebar_label: predicates +title: predicates Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 predicates config에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# predicates + +### 설명 {#description} + +@short: 선택 사항. 데이터 차원(행, 열)에 대한 사용자 정의 전처리 함수를 제공합니다 + +데이터가 적용되기 전에 어떻게 수정되어야 하는지를 정의합니다. + +### 사용법 {#usage} + +~~~jsx +predicates?: { + [key: string]: { + handler: (value: any) => any, + type: 'number' | 'date' | 'text' | [], + label?: string | (type: 'number' | 'date' | 'text') => string, + template?: (value: any, locale?: any) => string, + field?: (value:string) => boolean, + filter?: { + type: "number"|"text"|"date"|"tuple", + format?:(any) => string + } + } +}; +~~~ + +### 매개변수 {#parameters} + +이 속성은 키가 사용자 정의 함수의 이름이고, 값이 실제 함수 정의를 담은 객체인 객체입니다. predicate 객체는 여러 키-함수 쌍을 가질 수 있으며, 그 모두는 Pivot 구성에서 사용 가능합니다. 각 객체는 다음의 매개변수를 가집니다: + +- `label` - (선택 사항) 행/열의 데이터 수정 옵션 드롭다운 GUI에 표시되는 predicate의 레이블 +- `type` - (필수) 이 predicate가 적용될 수 있는 필드 유형을 정의합니다; "number", "date", "text" 또는 이들 값의 배열을 사용할 수 있습니다 +- `field` - (선택 사항) 지정한 필드의 데이터 처리 방법을 정의하는 함수로, 필드의 id를 매개변수로 받아 해당 필드에 predicate를 추가해야 하는 경우 **true**를 반환합니다 +- `filter` - (선택 사항) 기본적으로 필터 유형은 `type` 매개변수에서 가져오지만, 다른 유형이 필요한 경우 이 `filter` 객체를 사용할 수 있습니다. 다음 매개변수를 가집니다: + - `type` - (선택 사항) 적용될 필드 유형을 정의합니다: "number"|"text"|"date"|"tuple". "tuple"은 숫자 값에 적용되는 콤보 필터로, 데이터는 숫자 값으로 필터링되지만 필터에는 텍스트 값이 표시됩니다 + - `format` - (선택 사항) 필터 옵션 표시 형식을 정의하는 함수입니다; 형식이 정의되지 않은 경우 template 매개변수의 형식이 적용됩니다; 여기서(`filter` 객체의) `type`이 지정되지 않으면, predicate의 `type` 매개변수에 설정된 유형에 형식이 적용됩니다 +- `handler` - (사용자 정의 predicates에 필수) 데이터 처리 방법을 정의하는 함수입니다; 처리할 값을 단일 인수로 받아 처리된 값을 반환해야 합니다 +- `template` - (선택 사항) 데이터 표시 방법을 정의하는 함수입니다; 함수는 처리된 값을 반환하며, `handler`가 반환한 값을 받고, 필요한 경우 [`locale`](api/config/locale-property.md)을 사용하여 텍스트 값을 현지화할 수 있습니다 + +`predicates` 속성으로 predicate가 지정되지 않은 경우 다음의 기본 predicates가 적용됩니다: + +~~~jsx +const defaultPredicates = { + // 원시(처리되지 않은) 값을 나타내는 서비스 predicate + $empty: { label: (type) => `Raw ${type}`, type: ["number", "date", "text"] }, + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +## 예제 {#example} + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// 날짜 문자열을 Date로 변환 +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +**관련 문서**: [predicates로 데이터 처리하기](guides/working-with-data.md#processing-data-with-predicates) + +**관련 샘플**: [Pivot 2. 사용자 정의 predicates](https://snippet.dhtmlx.com/mhymus00) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/readonly-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/readonly-property.md new file mode 100644 index 0000000..faca09c --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/readonly-property.md @@ -0,0 +1,52 @@ +--- +sidebar_label: readonly +title: readonly Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 readonly 설정에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드하실 수 있습니다. +--- + +# readonly + +### 설명 {#description} + +@short: 선택 사항입니다. 읽기 전용 모드를 활성화하거나 비활성화합니다. + +읽기 전용 모드에서는 UI를 통해 Pivot 구조를 구성할 수 없습니다. + +### 사용법 {#usage} + +~~~jsx + readonly?: boolean; +~~~ + +### 파라미터 {#parameters} + +이 속성은 **true** 또는 **false**로 설정할 수 있습니다: + +- `true` - 읽기 전용 모드를 활성화합니다 +- `false` - 기본값으로, 읽기 전용 모드를 비활성화합니다 + +## 예제 {#example} + +~~~jsx {18} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + readonly: true +}); +~~~ + +**관련 샘플**: [Pivot 2. 읽기 전용 모드](https://snippet.dhtmlx.com/0k0mvycv) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md new file mode 100644 index 0000000..8dfae9b --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md @@ -0,0 +1,131 @@ +--- +sidebar_label: tableShape +title: tableShape Config +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 tableShape config에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 실행해 보세요. DHTMLX Pivot 30일 무료 평가판을 다운로드할 수도 있습니다. +--- + +# tableShape + +### 설명 {#description} + +@short: 선택 사항. Pivot 테이블의 외관을 구성합니다 + +### 사용법 {#usage} + +~~~jsx +tableShape?: { + templates?: { + [field: string]: ( + value: any, + operation: string + ) => any; + }, + totalRow?: boolean | "sumOnly", + totalColumn?: boolean | "sumOnly", + marks?: { + [cssClass: string]: ((v: any, columnData: any, rowData: any) => boolean) + | "max" + | "min" + }, + sizes?: { + rowHeight?: number, + headerHeight?: number, + columnWidth?: number, + footerHeight?: number + }, + tree?:boolean, + cleanRows?: boolean, + split?: { + left?: boolean, + right?: boolean, + }, + cellStyle?: ( + field: string, + value: any, + area: "rows"|"columns"|"values", + method?: string, + isTotal?: "row"|"column"|"both") + => string, +}; +~~~ + +### 매개변수 {#parameters} + +- `templates` - (선택 사항) 셀에 템플릿을 설정할 수 있습니다. 다음과 같은 구조의 객체입니다: + - 각 키는 필드 id입니다 + - 값은 셀 값과 연산을 인수로 받아 문자열을 반환하는 함수입니다. 지정된 필드를 기반으로 하는 모든 열에 해당 템플릿이 적용됩니다. 예를 들어 측정 단위를 설정하거나 숫자 값의 소수점 이하 자릿수를 지정하는 데 사용할 수 있습니다. 아래 예제를 참고하세요. +- `marks` - (선택 사항) 셀에 필요한 값을 표시할 수 있습니다. 키는 CSS 클래스 이름이고, 값은 함수 또는 미리 정의된 문자열("max", "min") 중 하나인 객체입니다. 함수는 검사된 값에 대해 boolean을 반환해야 합니다. **true**가 반환되면 해당 CSS 클래스가 셀에 적용됩니다. 예제를 포함한 자세한 내용은 [셀 스타일](guides/stylization.md#cell-style)을 참고하세요. +- `sizes` - (선택 사항) 테이블의 다음 크기 매개변수를 정의합니다: + - `rowHeight` - (선택 사항) Pivot 테이블의 행 높이(픽셀). 기본값은 34입니다 + - `headerHeight` - (선택 사항) 헤더 높이(픽셀). 기본값은 30입니다 + - `footerHeight` - (선택 사항) 푸터 높이(픽셀). 기본값은 30입니다 + - `columnWidth` - (선택 사항) 열 너비(픽셀). 기본값은 150입니다 +- `cellStyle` - (선택 사항) 셀에 사용자 정의 스타일을 적용하는 함수입니다. 함수의 매개변수는 다음과 같습니다: + - `field` - (필수) 스타일이 적용될 필드 이름을 나타내는 문자열 + - `value` - (필수) 셀의 값 (해당 행과 열의 실제 데이터) + - `area` - (필수) 셀이 속한 테이블 영역을 나타내는 문자열("rows", "columns" 또는 "values" 영역) + - `method` - (선택 사항) 셀에 수행되는 연산을 나타내는 문자열 (예: "sum", "count" 등) + - `isTotal` - (선택 사항) 셀이 합계 행, 합계 열 또는 둘 다에 속하는지 정의합니다: "row"|"column"|"both" + `cellStyle` 함수는 셀에 특정 스타일을 적용하는 CSS 클래스 이름으로 사용할 수 있는 문자열을 반환합니다. +- `tree` - (선택 사항) **true**로 설정하면 데이터를 확장 가능한 행으로 표시하는 트리 모드를 활성화합니다. 기본값은 **false**입니다. 예제를 포함한 자세한 내용은 [트리 모드로 전환](guides/configuration.md#enabling-the-tree-mode)을 참고하세요 +- `totalColumn` - (선택 사항) **true**이면 행의 합계 값이 포함된 합계 열을 생성합니다(기본값은 **false**). "sumOnly"로 설정하면 합계 값 열만 생성됩니다(sum 연산에서만 사용 가능합니다) +- `totalRow` - (선택 사항) **true**이면 합계 값이 포함된 푸터를 생성합니다(기본값은 **false**). "sumOnly"로 설정하면 합계 행 값만 포함된 행이 생성됩니다(sum 연산에서만 사용 가능합니다) +- `cleanRows` - (선택 사항) **true**로 설정하면 테이블 뷰에서 스케일 열의 중복 값이 숨겨집니다. 기본값은 **false**입니다 +- `split` - (선택 사항) 지정된 매개변수에 따라 오른쪽 또는 왼쪽 열을 고정할 수 있습니다([열 고정](guides/configuration.md#freezing-columns) 참고): + - `left` (boolean) - **true**(**false**가 기본값)로 설정하면 왼쪽 열이 고정되어 스크롤 중에도 열이 정적으로 표시됩니다. 분할되는 열의 수는 [`config`](api/config/config-property.md) 속성에 정의된 행 필드의 수와 동일합니다 + - `right` (boolean) - 오른쪽에 합계 열을 고정합니다. 기본값은 **false**입니다 + +기본적으로 `tableShape`는 undefined이며, 합계 행과 합계 열이 없고, 템플릿과 marks가 적용되지 않으며, 데이터는 트리가 아닌 테이블로 표시되고, 스크롤 중 열이 고정되지 않음을 의미합니다. + +## 예제 {#example} + +아래 예제에서는 *state* 셀에 템플릿을 적용하여 주의 전체 이름과 약어를 결합한 이름을 표시합니다. + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", +// other values, +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // "state" 셀 값을 커스터마이즈하는 템플릿 설정 + state: v => v+ ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // other values + ], + }, + fields, +}); +~~~ + +**관련 샘플**: + +- [Pivot 2. 트리 모드](https://snippet.dhtmlx.com/6ylkoukn) +- [Pivot 2. 고정 열](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. 행, 헤더, 푸터 높이 및 모든 열 너비 설정](https://snippet.dhtmlx.com/x46uyfy9) +- [Pivot 2. 행 정리](https://snippet.dhtmlx.com/rwwhgv2w?tag=pivot) +- [Pivot 2. 테이블 및 헤더 셀에 사용자 정의 CSS 추가](https://snippet.dhtmlx.com/nfdcs4i2) + +**관련 문서**: +- [구성](guides/configuration.md) +- [셀 스타일](guides/stylization.md#cell-style) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/add-field-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/add-field-event.md new file mode 100644 index 0000000..a0e72ec --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/add-field-event.md @@ -0,0 +1,74 @@ +--- +sidebar_label: add-field +title: add-field 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 add-field 이벤트에 대해 학습할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# add-field + +### 설명 {#description} + +@short: 행, 열 또는 값 영역에 새 필드가 추가될 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"add-field": ({ + id?: string | number, + area: string, + field: string | number, + method?: string +}) => boolean; +~~~ + +### 매개변수 {#parameters} + +이 액션의 callback은 다음 매개변수를 포함하는 객체를 받습니다: + +- `id` - (선택) 새 필드의 원하는 id; 설정하지 않으면 자동 생성된 id가 추가됩니다 +- `area` - (필수) 새 필드가 추가되는 영역의 이름으로, "rows", "columns" 또는 "values" 중 하나입니다 +- `field` - (필수) 필드의 이름 +- `method` - (선택) 데이터 집계 방법을 정의합니다 (지정하지 않으면 해당 데이터 유형에 적합한 첫 번째 방법이 설정됩니다); 다음 중 하나를 사용할 수 있습니다: + - **values** 영역에서는 필수이며, 데이터 연산 유형 중 하나를 나타내는 문자열입니다: [기본 메서드](guides/working-with-data.md#default-methods) + - **rows** 및 **columns** 영역에서는 선택 사항이며, 값이 설정된 경우 predicate입니다; 커스텀 predicate이거나 기본값 중 하나인 "year", "quarter", "month", "week", "day", "hour", "minute"를 사용할 수 있습니다. 기본적으로 원시 값이 설정됩니다. + 커스텀 predicate이나 method가 설정된 경우, [predicates](api/config/predicates-property.md) 또는 [methods](api/config/methods-property.md) 속성에 id를 지정해야 합니다. + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 예제 {#example} + +아래 예제에서는 [`api.intercept()`](api/internal/intercept-method.md) 메서드를 사용하여 **number** 데이터 유형의 값 필드에 새 메서드를 추가합니다: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//미리 정의된 method로 values 추가 +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "min"; + } +}); +~~~ + +**관련 문서**: [api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md new file mode 100644 index 0000000..526018d --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: apply-filter +title: apply-filter 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 apply-filter 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# apply-filter + +### 설명 {#description} + +@short: 필터가 적용될 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"apply-filter": ({ + rule: {} +}) => boolean | void; +~~~ + +### 매개변수 {#parameters} + +액션의 callback은 다음 매개변수를 포함하는 객체를 받습니다: + +- `rule` - 아래와 같은 매개변수를 포함하는 필터 구성 객체: + - `field` - (필수) 필터가 적용될 필드 id + - `filter` - (필수) 필터 유형: + - 텍스트 값의 경우: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith + - 숫자 값의 경우: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains + - 날짜 유형의 경우: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween + - `value` - (선택) 필터링 기준으로 사용할 값 + - `includes` - (선택) 이미 필터링된 값 중에서 표시할 값의 배열; 텍스트 및 날짜 값에 사용 가능 + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 예제 {#example} + +~~~jsx {20-23} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//필터가 적용된 필드의 레이블을 콘솔에 출력합니다 +table.api.on("apply-filter", (ev) => { + console.log("The field to which filter was applied:", ev.rule.field); +}); +~~~ + +**관련 문서**: [api.on()](api/internal/on-method.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md new file mode 100644 index 0000000..ea0b2cb --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md @@ -0,0 +1,82 @@ +--- +sidebar_label: delete-field +title: delete-field 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 delete-field 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# delete-field + +### 설명 {#description} + +@short: 필드를 제거할 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"delete-field": ({ + area: string, + id: string | number +}) => boolean | void; +~~~ + +### 파라미터 {#parameters} + +액션의 콜백은 다음 파라미터를 포함하는 객체를 받습니다: + +- `area` - (필수) 필드가 제거되는 영역의 이름으로, "rows", "columns" 또는 "values" 영역이 될 수 있습니다 +- `id` - (필수) 제거되는 필드의 id + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 예제 {#example} + +아래 예제에서는 [`api.exec()`](api/internal/exec-method.md) 메서드를 통해 `delete-field` 액션이 실행됩니다. **values** 영역에서 마지막 필드가 제거됩니다. [`api.getState()`](api/internal/getstate-method.md) 메서드는 Pivot [`config`](api/config/config-property.md)의 현재 상태를 가져오는 데 사용됩니다. 버튼을 클릭하면 액션이 실행됩니다. + +~~~jsx {31-34} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// API 메서드 호출: config의 values에서 특정 값 제거 +function removeLastField() { + if (table.api) { + const state = table.api.getState(); + const config = state.config; + + const count = config.values.length; + + if (count) { + const lastValue = config.values[count - 1]; + + table.api.exec("delete-field", { + area: "values", + id: lastValue.id, // config.values에 추가된 항목의 자동 생성 ID + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/move-field-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/move-field-event.md new file mode 100644 index 0000000..d2b9dd6 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/move-field-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: move-field +title: move-field 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리의 move-field 이벤트에 대한 내용을 문서에서 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# move-field + +### 설명 {#description} + +@short: 필드 순서를 변경할 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"move-field": ({ + area: string, + id: string | number, + before?: string, + after?: string +}) => void | boolean; +~~~ + +### 매개변수 {#parameters} + +action의 callback은 다음 매개변수를 포함하는 객체를 받습니다: + +- `area` - (필수) 순서 변경이 이루어지는 영역의 이름으로, "rows", "columns" 또는 "values" 영역이 될 수 있습니다 +- `id` - (필수) 이동되는 필드의 id +- `before` - (선택) 이동된 필드가 앞에 배치될 필드의 id +- `after` - (선택) 이동된 필드가 뒤에 배치될 필드의 id + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 예제 {#example} + +~~~jsx {20-23} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//순서가 변경된 필드의 id를 콘솔에 출력합니다 +table.api.on("move-field", (ev) => { + console.log("The id of the reordered field:", ev.id); +}); +~~~ + +**관련 문서**: [api.on()](api/internal/on-method.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md new file mode 100644 index 0000000..1624a46 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md @@ -0,0 +1,95 @@ +--- +sidebar_label: open-filter +title: open-filter 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 open-filter 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 탐색하고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수도 있습니다. +--- + +# open-filter + +### 설명 {#description} + +@short: 필드에 대한 필터가 활성화될 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"open-filter": ({ + id: string | null, + area?: "values" | "rows" | "columns" +}) => boolean | void; +~~~ + +### 매개변수 {#parameters} + +해당 action의 callback은 다음 매개변수를 받습니다: + +- `area` - 필드가 적용되는 영역("rows", "columns", "values") +- `id` - 필드의 id. null 값을 가진 단일 id 인수가 전달되면 필터가 닫힙니다. + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다. +::: + +### 반환값 {#returns} + +함수는 boolean 값 또는 void를 반환할 수 있습니다. **false**를 반환하면 해당 이벤트 동작이 중단됩니다. + +### 예제 {#example} + +아래 예제는 필터 박스를 닫을 때 Configuration 패널을 숨기는 방법을 보여줍니다: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + if(!ev.id) { + table.api.exec("show-config-panel", { + mode: false + }); + } +}); +~~~ + +다음 예제에서는 필터가 활성화된 필드의 id를 콘솔에 출력합니다: + +~~~jsx {20-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + console.log("The field id for which filter is activated:", ev.id); +}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/render-table-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/render-table-event.md new file mode 100644 index 0000000..588c297 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/render-table-event.md @@ -0,0 +1,178 @@ +--- +sidebar_label: render-table +title: render-table 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리의 문서에서 render-table 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot의 무료 30일 평가판을 다운로드하세요. +--- + +# render-table + +### 설명 {#description} + +@short: 위젯 구성이 처리된 후, 테이블이 렌더링되기 직전에 발생합니다 + +이 이벤트를 사용하면 최종 테이블 구성을 즉석에서 변경하거나 테이블 렌더링을 완전히 차단할 수 있습니다. + +### 사용법 {#usage} + +~~~jsx +"render-table": ({ + config: { + columns?: any[], + data?: any[], + footer?: boolean, + sizes?: { + rowHeight?: number, + headerHeight?: number, + columnWidth?: number, + footerHeight?: number + }, + split?: { + left?: number; + right?: number; + }, + tree?: boolean, + cellStyle?: (row: any, col: any) => string, + } +}) => boolean | void; +~~~ + +### 매개변수 {#parameters} + +액션의 callback은 다음 매개변수를 가진 `config` 객체를 받습니다: + +- `columns` - (선택) 각 객체에 대해 다음 매개변수를 포함하는 열 배열: + - `id` (number) - (필수) 열의 id + - `cell` (any) - (선택) 셀 내용이 담긴 템플릿 ([template 헬퍼를 통한 템플릿 추가](guides/configuration.md#adding-a-template-via-the-template-helper) 참조) + - `template` - (선택) [`tableShape`](api/config/tableshape-property.md) 속성을 통해 정의된 템플릿 + - `fields` (array) - (선택) 트리 모드의 계층형 열에서 필드를 정의합니다. 각 레벨에서 이 열에 표시되는 필드를 반영합니다 + - `field` - (선택) 필드의 id인 문자열 + - `method` (string) - (선택) 이 열의 필드에 대해 정의된 메서드 + - `methods` (array) - (선택) 트리 모드의 계층형 열에서 필드에 적용되는 메서드를 정의합니다 + - `format` (string or object) - (필수) 날짜 형식 또는 숫자 형식 ([필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields) 참조) + - `isNumeric` (boolean) - (선택) 열에 숫자 값이 포함되어 있는지 여부를 정의합니다 + - `isTotal` (boolean) - (선택) 합계 열인지 여부를 정의합니다 + - `area` (string) - (선택) 열이 렌더링되는 영역: "rows", "columns", "values" + - `header` - (선택) 각 셀에 대해 다음 속성을 포함하는 헤더 셀 배열: + - `text` (string) - (선택) 셀 텍스트, 또는 형식화된 값, 또는 predicate 템플릿으로 처리된 값 + - `rowspan` (number) - (선택) 헤더가 차지할 행 수 + - `colspan` (number) - (선택) 헤더가 차지할 열 수 + - `value` (any) - (필수) 셀이 "columns" 영역에 속하는 경우 원시 값 + - `field` (string) - (필수) 셀이 "columns" 영역에 속하는 경우 값이 표시되는 필드 + - `method` (string) - (필수) 셀이 "columns" 영역에 속하고 predicate가 정의된 경우 필드 predicate + - `format` (string or object) - 날짜 형식 또는 숫자 형식 ([필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields) 참조) + - `footer` - (선택) 헤더 레이블 또는 헤더 설정과 동일한 footer 설정을 포함하는 객체 + - `data` - (선택) 테이블 데이터를 포함하는 객체 배열; 각 객체는 하나의 행을 나타냅니다: + - `id` (number) - (필수) 행 id + - `values` (array) - (필수) 행 데이터를 포함하는 배열 + - `open` (boolean) - (선택) 브랜치 상태 + - `$level` (boolean) - (선택) 브랜치 인덱스 +- `footer` - (선택) **true**로 설정하면 테이블 하단에 footer가 표시됩니다; 기본값은 **false**이며 보이지 않습니다 +- `sizes` - (선택) 테이블 크기 설정을 포함하는 객체 (columnWidth, footerHeight, headerHeight, rowHeight) +- `split` (object) - (선택) 다음 속성을 포함하는 객체: + - `left` (number) - 왼쪽에서 고정할 열 수 + - `right` (number) - 오른쪽에서 고정할 열 수 +- `tree` - (선택) 트리 모드 활성화 여부를 정의합니다 (활성화된 경우 **true**) +- `cellStyle` - (선택) 셀에 커스텀 스타일을 적용하는 함수입니다. 행과 열 객체를 받아 CSS 클래스 이름 문자열을 반환합니다: `(row, col) => string` + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 반환값 {#returns} + +callback은 boolean 또는 void를 반환할 수 있습니다. +이벤트 핸들러가 **false**를 반환하면 해당 작업이 차단됩니다. 이 경우 테이블 렌더링이 방지됩니다. + +### 예제 {#example} + +다음 예제는 [`config`](api/config/config-property.md) 객체를 콘솔에 출력하고 footer를 추가하는 방법을 보여줍니다. + +~~~jsx {20-28} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.intercept("render-table", (ev) => { + console.log(ev.config); //config 객체 출력 + console.log(ev.config.columns); //columns 배열 출력 + + ev.config.footer = true; + ev.config.columns[0].footer = ["Custom footer"]; + + // 여기서 "false"를 반환하면 테이블 렌더링이 방지됩니다 +}); +~~~ + +다음 예제는 버튼 클릭으로 모든 행을 펼치거나 접는 방법을 보여줍니다. 트리 모드는 [`tableShape`](api/config/tableshape-property.md) 속성을 통해 활성화해야 합니다. + +~~~jsx +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true, + }, + fields, + data: dataset, + config: { + rows: ["type", "studio"], + columns: [], + values: [ + { + field: "score", + method: "max" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + }, + { + field: "episodes", + method: "count" + } + ] + } +}); + +const api = table.api; +const tableApi = api.getTable(); + +// 테이블 구성 업데이트 시 모든 테이블 브랜치를 닫힌 상태로 설정 +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // 여기서 "false"를 반환하면 테이블 렌더링이 방지됩니다 + // return false; +}); + +function openAll() { + tableApi.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableApi.exec("close-row", { id: 0, nested: true }); +} +~~~ + +`render-table` 이벤트를 사용하여 열 고정 기능을 구성하는 방법도 참조하세요: [열 고정](guides/configuration.md#freezing-columns). + +**관련 글**: [pivot.template 헬퍼](api/helpers/template.md) + +**관련 샘플**: [Pivot 2. 커스텀 고정(고정) 열 (사용자 지정 수)](https://snippet.dhtmlx.com/53erlmgp) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md new file mode 100644 index 0000000..f0dc2a5 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md @@ -0,0 +1,60 @@ +--- +sidebar_label: show-config-panel +title: show-config-panel 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 show-config-panel 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 사용해 보세요. DHTMLX Pivot 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# show-config-panel + +### 설명 {#description} + +@short: 구성 패널의 표시 여부가 변경될 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"show-config-panel": ({ + mode: boolean +}) +~~~ + +### 매개변수 {#parameters} + +이 액션의 콜백은 다음 매개변수를 포함하는 객체를 받습니다: + +- `mode` - (필수) 값이 **true**(기본값)로 설정되면 구성 패널이 표시되고, **false**로 설정되면 구성 패널이 숨겨집니다 + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 예제 {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//구성 패널 숨기기 +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +**관련 문서**: +- [`showConfigPanel()` 메서드](api/methods/showconfigpanel-method.md) +- [`configPanel` 속성](api/config/configpanel-property.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/update-config-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/update-config-event.md new file mode 100644 index 0000000..f432a3c --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/update-config-event.md @@ -0,0 +1,78 @@ +--- +sidebar_label: update-config +title: update-config 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리의 update-config 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 30일 무료 평가판을 다운로드할 수도 있습니다. +--- + +# update-config + +### 설명 {#description} + +@short: Pivot UI를 통해 행, 열 또는 집계 함수를 수정할 때 발생합니다 + +이 액션은 사용자의 집계 구성을 저장하는 데 유용하며, 다음에 위젯을 사용할 때 해당 구성을 적용하여 사용자가 이전 작업을 이어서 진행할 수 있도록 합니다. + +### 사용법 {#usage} + +~~~jsx +"update-config": ({ + rows: string[], + columns: string[], + values: [], + filters: {} +}) => boolean | void; +~~~ + +### 매개변수 {#parameters} + +이 액션의 콜백은 처리된 [`config`](api/config/config-property.md) 매개변수를 포함하는 객체를 받습니다: + +- `rows` - Pivot 테이블의 행. 필드 ID와 데이터 추출 메서드를 포함하는 객체이며, 객체의 매개변수는 다음과 같습니다: + - `field` - 필드의 ID + - `method` - 데이터 추출 메서드 (시간 기반 데이터 필드에 사용) +- `columns` - Pivot 테이블의 열을 정의합니다. 필드 ID와 데이터 추출 메서드를 포함하는 객체이며, 객체의 매개변수는 다음과 같습니다: + - `field` - 필드의 ID + - `method` - 데이터 추출 메서드를 정의합니다 (시간 기반 데이터 필드에 사용). + 기본적으로 시간 기반 필드(**date** 타입)에 대해 "year", "quarter", "month", "week", "day", "hour", "minute" 값을 가진 메서드를 사용할 수 있습니다 +- `values` - Pivot 테이블 셀의 데이터 집계를 정의합니다. 필드 ID와 데이터 집계 메서드를 포함하는 객체이며, 객체의 매개변수는 다음과 같습니다: + - `field` - 필드의 ID + - `method` - 데이터 추출 메서드를 정의합니다. 메서드와 가능한 옵션에 대해서는 [메서드 적용](guides/working-with-data.md#default-methods)을 참조하세요 +- `filters` - (선택 사항) 테이블에서 데이터가 필터링되는 방식을 정의합니다. 필드 ID와 데이터 집계 메서드를 포함하는 객체입니다. `filter` 객체에 대한 설명은 [`config`](api/config/config-property.md)를 참조하세요 + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 반환값 {#returns} + +콜백은 boolean 또는 void를 반환할 수 있습니다. +이벤트 핸들러 함수가 *false*를 반환하면, 이벤트를 트리거한 작업이 차단되고 `update-config` 작업이 중단됩니다. + +### 예제 {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//config 객체를 콘솔에 출력합니다 +table.api.on("update-config", (config) => { + console.log("Config has changed", config); +}); +~~~ + +**관련 문서**: [api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/events/update-field-event.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/update-field-event.md new file mode 100644 index 0000000..dec534f --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/events/update-field-event.md @@ -0,0 +1,67 @@ +--- +sidebar_label: update-field +title: update-field 이벤트 +description: DHTMLX JavaScript Pivot 라이브러리의 update-field 이벤트에 대한 문서를 확인할 수 있습니다. 개발자 가이드 및 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# update-field + +### 설명 {#description} + +@short: 필드가 업데이트될 때 발생합니다 + +### 사용법 {#usage} + +~~~jsx +"update-field": ({ + id: string | number, + method: string, + area: string +}) => boolean; +~~~ + +### 매개변수 {#parameters} + +액션의 callback은 다음 매개변수를 포함하는 객체를 받습니다: + +- `id` - (필수) 업데이트되는 필드의 id +- `method` - (필수) 다음 중 하나의 method를 사용할 수 있습니다: + - **values** 영역의 경우, 데이터 연산 유형 중 하나를 나타내는 문자열입니다: [기본 메서드](guides/working-with-data.md#default-methods) + - **rows** 및 **columns** 영역의 경우, 데이터 predicate 값으로 "year", "quarter", "month", "week", "day", "hour", "minute" 중 하나를 사용할 수 있습니다. 기본적으로 원시 값이 설정됩니다. + 커스텀 predicate 또는 method가 설정된 경우, [predicate](api/config/predicates-property.md) 또는 [methods](api/config/methods-property.md) 속성에 id를 지정해야 합니다. +- `area` - (필수) 필드가 업데이트되는 영역의 이름으로, "rows", "columns" 또는 "values" 영역을 지정합니다 + +:::info +내부 이벤트를 처리하려면 [Event Bus 메서드](api/overview/internal-eventbus-overview.md)를 사용할 수 있습니다 +::: + +### 예제 {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//업데이트된 필드의 id를 콘솔에 출력합니다 +table.api.on("update-field", (ev) => { + console.log("The id of the field that was updated:", ev.id); +}); +~~~ + +**관련 문서**: +- [api.on()](api/internal/on-method.md) +- [methods](api/config/methods-property.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/helpers/template.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/helpers/template.md new file mode 100644 index 0000000..f69e40d --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/helpers/template.md @@ -0,0 +1,89 @@ +--- +sidebar_label: template +title: template +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 Pivot template 헬퍼에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 탐색하고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +### 설명 {#description} + +`template` 함수는 테이블 헤더 셀과 본문 셀에 템플릿을 적용할 수 있게 합니다. + +### 사용법 {#usage} + +본문 셀의 경우: + +~~~jsx +pivot.template({value, method, row, column}) => string; +~~~ + +헤더 셀의 경우: + +~~~jsx +pivot.template({value, field, method, cell, column}) => string; +~~~ + +### 파라미터 {#parameters} + +본문 셀의 경우 함수는 다음 파라미터를 받습니다: + +- `value` (any) - (필수) 셀의 원시 값 +- `method` (string) - (필수) 열에 사용되는 메서드 또는 predicate +- `row` - (필수) 행 데이터를 담은 객체: + - `id` (number) - (필수) 행 id + - `values` (array) - (필수) 행 데이터를 담은 배열 + - `open` (boolean)- (선택) 브랜치 상태 + - `$level` (boolean)- (선택) 브랜치 인덱스 +- `column` - (필수) 열 데이터를 담은 객체: + - `id` (number) - (필수) 열의 id + - `cell` (any) - (선택) 셀 콘텐츠를 가진 템플릿 ([template 헬퍼를 통한 템플릿 추가](guides/configuration.md#adding-a-template-via-the-template-helper) 참조) + - `template` - (선택) [`tableShape`](api/config/tableshape-property.md) 프로퍼티를 통해 정의된 템플릿 + - `fields` (array) - (선택) 트리 모드에서 계층형 열의 필드를 정의합니다. 서로 다른 레벨에서 이 열에 표시되는 필드를 반영합니다 + - `field` - (선택) 필드 id인 문자열 + - `method` (string) - (선택) 이 열의 필드에 대해 정의된 경우의 메서드 + - `methods` (array) - (선택) 트리 모드에서 계층형 열의 필드에 적용되는 메서드를 정의합니다 + - `format` (string or object) - (필수) 날짜 형식 또는 숫자 형식 ([필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields) 참조) + - `isNumeric` (boolean) - (선택) 열이 숫자 값을 포함하는지 여부를 정의합니다 + - `isTotal` (boolean) - (선택) 합계 열인지 여부를 정의합니다 + - `area` (string) - (선택) 열이 렌더링되는 영역: "rows", "columns", "values" + - `header`- (선택) 각 셀에 대해 다음 프로퍼티를 가진 헤더 셀 배열: + - `text` (string) - (선택) 셀 텍스트, 형식화된 값, 또는 predicate 템플릿으로 처리된 값 + - `rowspan` (number) - (선택) 헤더가 걸쳐야 하는 행 수 + - `colspan` (number) - (선택) 헤더가 걸쳐야 하는 열 수 + - `value` (any) - (필수) 셀이 "columns" 영역에 속하는 경우의 원시 값 + - `field` (string) - (필수) 셀이 "columns" 영역에 속하는 경우 표시되는 값의 필드 + - `method` (string) - (필수) 셀이 "columns" 영역에 속하고 predicate가 정의된 경우의 필드 predicate + - `format` (string or object) - 날짜 형식 또는 숫자 형식 ([필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields) 참조) + +헤더 셀의 경우 함수 파라미터는 다음과 같습니다: + +- `value` (any) - (필수) 셀의 원시 값 +- `method` (string) - (선택) 열에 사용되는 predicate +- `field` (string) - (선택) 셀에 표시되는 값의 필드 +- `cell` - (필수) 셀 데이터를 담은 객체: + - `text` (string) - (선택) 셀 텍스트, 형식화된 값, 또는 predicate 템플릿으로 처리된 값 + - `rowspan` (number) - (선택) 헤더가 걸쳐야 하는 행 수 + - `colspan` (number) - (선택) 헤더가 걸쳐야 하는 열 수 + - `value` (any) - (필수) 셀이 "columns" 영역에 속하는 경우의 원시 값 + - `field` (string) - (필수) 셀이 "columns" 영역에 속하는 경우 표시되는 값의 필드 + - `method` (string) - (필수) 셀이 "columns" 영역에 속하고 predicate가 정의된 경우의 필드 predicate + - `format` (string or object) - (필수) 날짜 형식 또는 숫자 형식 ([필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields) 참조) +- `column` - (필수) 열 데이터를 담은 객체 (본문 셀과 동일) + +### 예제 {#example} + +아래 스니펫은 `pivot.template` 헬퍼를 통해 템플릿을 정의하는 방법을 보여줍니다. 헬퍼는 테이블이 렌더링되기 직전에 적용되며, 이는 [api.intercept()](api/internal/intercept-method.md) 메서드를 사용하여 [render-table](api/events/render-table-event.md) 이벤트를 인터셉트함으로써 이루어집니다. + +스니펫은 다음 항목에 아이콘을 추가하는 방법을 보여줍니다: + +- 필드(id, user_score)를 기반으로 한 본문 셀 (템플릿이 깃발 및 별 아이콘을 추가) +- 필드 이름을 기반으로 한 헤더 레이블 (예: 필드가 "id"인 경우 헤더 값 옆에 지구본 아이콘 추가) +- 값을 기반으로 한 열 헤더 (색상이 있는 화살표 표시기 추가) + + + + +**관련 문서**: + +- [`render-table`](api/events/render-table-event.md) +- [셀에 템플릿 적용](guides/configuration.md#applying-templates-to-cells) +- [헤더에 템플릿 적용](guides/configuration.md#applying-templates-to-headers) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/detach-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/detach-method.md new file mode 100644 index 0000000..8da55e7 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/detach-method.md @@ -0,0 +1,69 @@ +--- +sidebar_label: api.detach() +title: detach 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 detach 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# api.detach() + +## 설명 {#description} + +@short: 액션 핸들러를 제거하거나 분리할 수 있습니다 + +## 사용법 {#usage} + +~~~jsx +api.detach(tag: number | string ): void; +~~~ + +## 매개변수 {#parameters} + +- `tag` - 액션 태그의 이름 + +### 예제 {#example} + +아래 예제에서는 [`api.on()`](api/internal/on-method.md) 핸들러에 **tag** 속성을 포함한 객체를 추가한 후, `api.detach()` 메서드를 사용하여 [`open-filter`](api/events/open-filter-event.md) 액션의 로깅을 중지합니다. + +~~~jsx {31-34} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 핸들러 추가 +if (table.api) { + table.api.on( + "open-filter", + ({ area }) => { + console.log("Opened: " + area); + }, + { tag: "track" } + ); +} + +// 핸들러 분리 +function stop() { + table.api.detach("track"); +} + +const button = document.createElement("button"); + +button.addEventListener("click", stop); +button.textContent = "Stop logging"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/exec-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/exec-method.md new file mode 100644 index 0000000..3dc1458 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/exec-method.md @@ -0,0 +1,83 @@ +--- +sidebar_label: api.exec() +title: exec 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 exec 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# api.exec() + +### 설명 {#description} + +@short: 내부 이벤트를 트리거할 수 있습니다 + +## 사용법 {#usage} + +~~~jsx +api.exec( + event: string, + config: object +): Promise; +~~~ + +## 매개변수 {#parameters} + +- `event` - (필수) 발생시킬 이벤트 +- `config` - (필수) 매개변수가 포함된 config 객체 (발생시킬 이벤트 참조) + +## 액션 {#actions} + +:::info +Pivot 이벤트의 전체 목록은 [**여기**](api/overview/events-overview.md)에서 확인할 수 있습니다 +::: + +## 예제 {#example} + +아래 예제에서는 `api.exec()` 메서드를 통해 [`delete-field`](api/events/delete-field-event.md) 이벤트가 트리거됩니다. **values** 영역에서 마지막 필드가 제거됩니다. [`api.getState()`](api/internal/getstate-method.md) 메서드는 Pivot [`config`](api/config/config-property.md)의 현재 상태를 가져오는 데 사용됩니다. 버튼 클릭 시 이벤트가 트리거됩니다. + +~~~jsx {32-35} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//API 메서드 호출: config의 values에서 특정 값 제거 +function removeLastField() { + if (table.api) { + const state = table.api.getState(); + const config = state.config; + + const count = config.values.length; + + if (count) { + const lastValue = config.values[count - 1]; + + table.api.exec("delete-field", { + area: "values", + id: lastValue.id, // config.values에 추가된 항목의 자동 생성 ID + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md new file mode 100644 index 0000000..3e8f6c1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md @@ -0,0 +1,71 @@ +--- +sidebar_label: api.getReactiveState() +title: getReactiveState 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 getReactiveState 메서드에 대해 학습할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 사용해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# api.getReactiveState() + +### 설명 {#description} + +@short: Pivot의 반응형 속성을 담은 객체를 가져옵니다 + +### 사용법 {#usage} + +~~~jsx +api.getReactiveState(): object; +~~~ + +### 반환값 {#returns} + +이 메서드는 다음 매개변수를 포함하는 객체를 반환합니다: + +~~~jsx +{ + config: {}, // 현재 설정 (행, 열, 값, 필터) + activeFilter: {}, // 활성 필터 객체 (필터가 열려 있는 경우) + columnShape: {}, // Pivot 열 구성 + data: [], // 소스 데이터 + fields: [], // 필드 배열 + filters: {}, // 필터링 규칙 + headerShape: {}, // 테이블 헤더 설정 + predicates: {}, // 필드별 사용 가능한 조건자 + limits: {}, // 데이터셋의 행과 열 최대 개수 제한 + methods: {}, // 데이터 집계 메서드 + tableShape: {}, // 테이블 설정 (크기, 합계 행, 템플릿) + tableConfig: {}, // 테이블 구성 설정 (열, 데이터, 크기, 트리 모드, 푸터) + configPanel: boolean, // 구성 패널의 표시 상태 + readonly: boolean, // 읽기 전용 모드 활성화 여부 +} +~~~ + +### 예제 {#example} + +~~~jsx {21-26} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 반응형 config 스토어를 구독하고 변경될 때마다 로그를 출력합니다 +const state = table.api.getReactiveState(); + +state.config.subscribe((config) => { + console.log("Pivot config changed. Its current state:", config); +}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md new file mode 100644 index 0000000..1317e2a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md @@ -0,0 +1,67 @@ +--- +sidebar_label: api.getState() +title: getState 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 getState 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# api.getState() + +### 설명 {#description} + +@short: Pivot의 StateStore 프로퍼티가 담긴 객체를 반환합니다 + +### 사용법 {#usage} + +~~~jsx +api.getState(): object; +~~~ + +### 반환값 {#returns} + +이 메서드는 다음 파라미터를 포함하는 객체를 반환합니다: + +~~~jsx +{ + config: {}, // 현재 config (rows, columns, values, filters) + activeFilter: {}, // 활성 필터 객체 (필터가 열려 있는 경우) + columnShape: {}, // pivot 열 구성 + data: [], // 소스 데이터 + fields: [], // fields 배열 + filters: {}, // 필터링 규칙 + headerShape: {}, // 테이블 헤더 설정 + predicates: {}, // 필드별 사용 가능한 predicates + limits: {}, // 데이터셋의 행과 열 최대 개수 제한 + methods: {}, // 데이터 집계 메서드 + tableShape: {}, // 테이블 설정 (크기, 합계 행, 템플릿) + tableConfig: {}, // 테이블 구성 설정 (columns, data, 크기, 트리 모드, footer) + configPanel: boolean, // 구성 패널 표시 여부 상태 + readonly: boolean, // 읽기 전용 모드 활성화 여부 +} +~~~ + +### 예제 {#example} + +~~~jsx {21-22} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +const { config } = table.api.getState(); +console.log(config); //config 상태를 콘솔에 출력 +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md new file mode 100644 index 0000000..8eb55f5 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md @@ -0,0 +1,54 @@ +--- +sidebar_label: api.getStores() +title: getStores 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 getStores 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# api.getStores() + +### 설명 {#description} + +@short: Pivot의 DataStore 속성을 담은 객체를 반환합니다 + +### 사용법 {#usage} + +~~~jsx +api.getStores(): object; +~~~ + +### 반환값 {#returns} + +이 메서드는 **DataStore** 매개변수를 담은 객체를 반환합니다: + +~~~jsx +{ + data: DataStore // ( 매개변수 객체 ) +} +~~~ + +### 예제 {#example} + +~~~jsx {21-22} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +const stores = table.api.getStores(); +console.log("DataStore:", stores); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md new file mode 100644 index 0000000..4b49dad --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md @@ -0,0 +1,68 @@ +--- +sidebar_label: api.intercept() +title: intercept 메서드 +description: DHTMLX JavaScript Pivot 라이브러리의 intercept 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판을 다운로드하실 수 있습니다. +--- + +# api.intercept() + +### 설명 {#description} + +@short: 내부 이벤트를 가로채고 차단할 수 있습니다 + +### 사용법 {#usage} + +~~~jsx +api.intercept( + event: string, + callback: function, + config?: { tag?: number | string | symbol } +): void; +~~~ + +### 매개변수 {#parameters} + +- `event` - (필수) 발생시킬 이벤트 +- `callback` - (필수) 실행할 callback (callback 인수는 발생하는 이벤트에 따라 달라집니다) +- `config` - (선택) 다음 매개변수를 저장하는 객체: + - `tag` - (선택) 액션 태그. [`detach`](api/internal/detach-method.md) 메서드를 통해 액션 핸들러를 제거할 때 태그 이름을 사용할 수 있습니다 + +### 이벤트 {#events} + +:::info +Pivot 내부 이벤트의 전체 목록은 [**여기**](api/overview/main-overview.md#pivot-events)에서 확인할 수 있습니다. +액션을 수정하지 않고 수신만 하려면 [`api.on()`](api/internal/on-method.md) 메서드를 사용하세요. 액션을 변경하려면 `api.intercept()` 메서드를 적용하세요. +::: + +### 예제 {#example} + +아래 예제는 초기화 시 모든 접을 수 있는 행을 닫는 방법을 보여줍니다. + +~~~jsx {21-24} +// create Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//make all rows close at the initialization +table.api.intercept("render-table", (ev) => { + ev.config.data.forEach((row) => (row.open = false)); +}, {tag: "render-table-tag"}); +~~~ + +**관련 아티클**: [`render-table`](api/events/render-table-event.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/on-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/on-method.md new file mode 100644 index 0000000..81c5208 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/on-method.md @@ -0,0 +1,72 @@ +--- +sidebar_label: api.on() +title: on 메서드 +description: DHTMLX JavaScript Pivot 라이브러리의 on 메서드에 대한 문서에서 자세한 내용을 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# api.on() + +### 설명 {#description} + +@short: 내부 이벤트에 핸들러를 연결할 수 있습니다 + +### 사용법 {#usage} + +~~~jsx +api.on( + event: string, + handler: function, + config?: { intercept?: boolean, tag?: number | string | symbol } +): void; +~~~ + +### 파라미터 {#parameters} + +- `event` - (필수) 발생시킬 이벤트 +- `handler` - (필수) 연결할 핸들러 (핸들러 인수는 발생하는 이벤트에 따라 달라집니다) +- `config` - (선택) 다음 파라미터를 저장하는 객체: + - `intercept` - (선택) 이벤트 리스너 생성 시 `intercept: true`를 설정하면, 해당 이벤트 리스너가 다른 모든 리스너보다 먼저 실행됩니다 + - `tag` - (선택) 액션 태그. 태그 이름을 사용하여 [`detach`](api/internal/detach-method.md) 메서드로 액션 핸들러를 제거할 수 있습니다 + +### Events {#events} + +:::info +Pivot 내부 이벤트의 전체 목록은 [**여기**](api/overview/main-overview.md#pivot-events)에서 확인할 수 있습니다. +액션을 수정하지 않고 리스닝만 하려면 `api.on()` 메서드를 사용하세요. 액션을 변경하려면 [`api.intercept()`](api/internal/intercept-method.md) 메서드를 적용하세요. +::: + +### 예제 {#example} + +아래 예제는 필터가 활성화된 필드의 레이블을 출력하는 방법을 보여줍니다: + +~~~jsx {21-29} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + if (ev.id) { + const { config } = table.api.getState(); + const fieldObj = config[ev.area].find((f) => f.id === ev.id); + if (fieldObj) { + console.log("The field for which filter was activated:", fieldObj.label); + } + } +}, {tag: "open-filter-tag"}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md new file mode 100644 index 0000000..7cafbec --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md @@ -0,0 +1,45 @@ +--- +sidebar_label: api.setNext() +title: setNext 메서드 +description: DHTMLX JavaScript Pivot 라이브러리의 setNext 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 참고하고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# api.setNext() + +### 설명 {#description} + +@short: Event Bus 순서에 특정 액션을 추가할 수 있습니다 + +### 사용법 {#usage} + +~~~jsx +api.setNext(next: any): void; +~~~ + +### 매개변수 {#parameters} + +- `next` - (필수) **Event Bus** 순서에 포함할 액션 + +### 예제 {#example} + +아래 예제는 `api.setNext()` 메서드를 사용하여 사용자 정의 클래스를 Event Bus 순서에 통합하는 방법을 보여줍니다: + +~~~jsx {13-14} +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +// ServerDataService라는 사용자 정의 서버 서비스 클래스가 있다고 가정합니다 +const someServerService = new ServerDataService(server); + +Promise.all([ + fetch(server + "/data").then((res) => res.json()), + fetch(server + "/fields").then((res) => res.json()) +]).then(([data, fields]) => { + table.setConfig({ data, fields }); + + // serverDataService를 위젯의 Event Bus 순서에 통합합니다 + table.api.setNext(someServerService); +}); +~~~ + +**관련 문서**: [`setConfig`](api/methods/setconfig-method.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md new file mode 100644 index 0000000..07420b1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md @@ -0,0 +1,75 @@ +--- +sidebar_label: getTable() +title: getTable 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 getTable 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# getTable() + +### 설명 {#description} + +@short: Pivot 테이블의 내부 Table 위젯 인스턴스에 접근합니다 + +이 메서드는 Pivot 내부의 Table 위젯 인스턴스에 접근해야 할 때 사용됩니다. Table 기능에 직접 접근하여 데이터 직렬화 및 다양한 형식으로의 내보내기 등의 작업을 수행할 수 있습니다. Table API에는 자체 `api.exec()` 메서드가 있으며, [`open-row`](api/table/open-row.md), [`close-row`](api/table/close-row.md), [`export`](api/table/export.md), [`filter-rows`](api/table/filter-rows.md) 이벤트를 호출할 수 있습니다. + +### 사용법 {#usage} + +~~~jsx +getTable(wait:boolean): Table | Promise; +~~~ + +### 매개변수 {#parameters} + +`wait` - Table API가 Pivot에서 사용 가능해질 때까지 기다릴지 여부를 정의합니다(Pivot 초기화 중에 Table API를 사용할 때 필요합니다). 값이 **true**로 설정되면, 메서드는 Table API와 함께 promise를 반환합니다. + +### 예제 {#example} + +아래 예제에서는 Table 위젯 API에 접근하고, [`api.exec()`](api/internal/exec-method.md) 메서드를 사용하여 버튼 클릭으로 Table `export` 이벤트를 트리거합니다. + +~~~jsx +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// table 인스턴스에 접근 +let table_instance = table.getTable(); + +function toCSV() { + table_instance.exec("export", { + options: { + format: "csv", + cols: ";" + } + }); +} + +const exportButton = document.createElement("button"); + +exportButton.addEventListener("click", toCSV); +exportButton.textContent = "Export"; + +document.body.appendChild(exportButton); +~~~ + +**관련 문서**: + +- [`close-row`](api/table/close-row.md) +- [`export`](api/table/export.md) +- [`filter-rows`](api/table/filter-rows.md) +- [`open-row`](api/table/open-row.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md new file mode 100644 index 0000000..7053800 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md @@ -0,0 +1,73 @@ +--- +sidebar_label: setConfig() +title: setConfig() +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 setConfig() 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# setConfig() + +### 설명 {#description} + +@short: Pivot 위젯의 현재 구성을 업데이트합니다 + +이 메서드는 Pivot 위젯의 현재 구성을 업데이트하는 데 사용됩니다. 위젯의 기본 데이터 세트를 업데이트해야 할 때 유용합니다. 이 메서드는 `setConfig` 호출에서 명시적으로 제공되지 않은 이전에 설정된 모든 옵션을 보존합니다. + +### 사용법 {#usage} + +~~~jsx +setConfig(config: { [key:any]: any }): void; +~~~ + +### 매개변수 {#parameters} + +- `config` - (필수) Pivot 구성 객체입니다. 전체 속성 목록은 [여기](api/overview/properties-overview.md)를 참조하세요 + +:::important +이 메서드는 전달한 매개변수만 변경합니다. 현재 컴포넌트를 삭제하고 새 컴포넌트를 초기화합니다. +::: + +### 예제 {#example} + +~~~jsx {21-41} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 구성 매개변수 업데이트 +table.setConfig({ + config: { + rows: ["studio", "genre", "duration"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + { + field: "type", + method: "count" + } + ] + } +}); +~~~ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md new file mode 100644 index 0000000..32ace82 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md @@ -0,0 +1,56 @@ +--- +sidebar_label: setLocale() +title: setLocale() +description: DHTMLX JavaScript Pivot 라이브러리의 공식 문서에서 setLocale() 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 확인하거나 DHTMLX Pivot 무료 30일 평가판을 다운로드하세요. +--- + +# setLocale() + +### 설명 {#description} + +@short: Pivot에 새 로케일을 적용합니다 + +### 사용법 {#usage} + +~~~jsx +setLocale(null | locale?: object): void; +~~~ + +### 매개변수 {#parameters} + +- `null` - (선택 사항) 기본 로케일(영어)로 초기화합니다 +- `locale` - (선택 사항) 적용할 새 로케일의 데이터 객체 + +### 예제 {#example} + +~~~jsx +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// Pivot에 "de" 로케일 적용 +table.setLocale(pivot.locales.de); + +// Pivot에 기본 로케일 적용 +table.setLocale(); // 또는 setLocale(null); +~~~ + +**관련 문서**: +- [로컬라이제이션](guides/localization.md) +- [`locale`](api/config/locale-property.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md new file mode 100644 index 0000000..d488c1b --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md @@ -0,0 +1,55 @@ +--- +sidebar_label: showConfigPanel() +title: showConfigPanel() +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 showConfigPanel() 메서드에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 확인하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# showConfigPanel() + +### 설명 {#description} + +@short: 구성 패널을 표시하거나 숨깁니다. + +이 메서드는 사용자 상호작용 없이 구성 패널의 표시 여부를 제어해야 할 때 유용합니다. 예를 들어, 애플리케이션의 다른 상호작용이나 상태에 따라 패널을 숨기거나 표시할 수 있습니다. + +### 사용법 {#usage} + +~~~jsx +showConfigPanel({mode: boolean}): void; +~~~ + +### 매개변수 {#parameters} + +- `mode` (boolean) - (필수) 값이 **true**(기본값)로 설정되면 구성 패널이 표시되고, **false**로 설정되면 구성 패널이 숨겨집니다. + +### 예제 {#example} + +~~~jsx {21-23} +// Pivot 생성 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.showConfigPanel ({ + mode: false +}) +~~~ + +**관련 문서**: +- [`show-config-panel` 이벤트](api/events/show-config-panel-event.md) +- [`configPanel` 속성](api/config/configpanel-property.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/events-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/events-overview.md new file mode 100644 index 0000000..37c1fbf --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/events-overview.md @@ -0,0 +1,19 @@ +--- +sidebar_label: Events 개요 +title: Events 개요 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 Events 개요를 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판을 다운로드할 수도 있습니다. +--- + +# Events 개요 + +| 이름 | 설명 | +| ------------------------------------------------- | ----------------------------------------------- | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md new file mode 100644 index 0000000..5f3be78 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md @@ -0,0 +1,15 @@ +--- +sidebar_label: Event Bus 메서드 +title: Event Bus 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 내부 Event Bus 메서드 개요를 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# Event Bus 메서드 개요 {#event-bus-methods-overview} + +| 이름 | 설명 | +| ------------------------------------------------- | ------------------------------------------------- | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md new file mode 100644 index 0000000..60f90cd --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md @@ -0,0 +1,13 @@ +--- +sidebar_label: State 메서드 +title: State 메서드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 내부 State 메서드 개요를 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# State 메서드 개요 {#state-methods-overview} + +| 이름 | 설명 | +| ---------------------------------------------- | -------------------------------------------------- | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/main-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/main-overview.md new file mode 100644 index 0000000..8619b68 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/main-overview.md @@ -0,0 +1,80 @@ +--- +sidebar_label: API 개요 +title: API 개요 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 API 개요를 확인할 수 있습니다. 개발자 가이드와 API 참조를 살펴보고, 코드 예제와 라이브 데모를 직접 실행해 보세요. DHTMLX Pivot의 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# API 개요 {#api-overview} + +## Pivot 생성자 {#pivot-constructor} + +~~~jsx +new pivot.Pivot("#root", { + // 구성 파라미터 +}); +~~~ + +**파라미터**: + +- HTML 컨테이너 (HTML 컨테이너의 ID) +- 구성 파라미터 객체 ([여기서 확인](#pivot-properties)) + +## Pivot 메서드 {#pivot-methods} + +| 이름 | 설명 | +| ------------------------------------------- | ------------------------------------------ | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | + +## Pivot 내부 API {#pivot-internal-api} + +### Event Bus 메서드 {#event-bus-methods} + +| 이름 | 설명 | +| :------------------------------------ | :------------------------------------------- | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | + +### State 메서드 {#state-methods} + +| 이름 | 설명 | +| :---------------------------------------------- | :------------------------------------------------- | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | + +## Pivot 이벤트 {#pivot-events} + +| 이름 | 설명 | +| :------------------------------------------------ | :---------------------------------------------- | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | + +## Pivot 속성 {#pivot-properties} + +| 이름 | 설명 | +| :------------------------------------------------- | :----------------------------------------------- | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md new file mode 100644 index 0000000..284bf03 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md @@ -0,0 +1,14 @@ +--- +sidebar_label: Methods overview +title: 메서드 개요 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 메서드 개요를 확인할 수 있습니다. 개발자 가이드 및 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수도 있습니다. +--- + +# 메서드 개요 {#methods-overview} + +| 이름 | 설명 | +| ------------------------------------------- | ----------------------------------------------- | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md new file mode 100644 index 0000000..646458f --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md @@ -0,0 +1,24 @@ +--- +sidebar_label: Properties overview +title: Properties 개요 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 Properties 개요를 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# Properties 개요 + +**Pivot**을 구성하려면 [구성](guides/configuration.md) 섹션을 참조하십시오. + +| 이름 | 설명 | +| -------------------------------------------------- | ------------------------------------------------ | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md new file mode 100644 index 0000000..5f8963b --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md @@ -0,0 +1,16 @@ +--- +sidebar_label: Table 이벤트 개요 +title: Table 이벤트 개요 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 JavaScript Pivot의 Table 이벤트 개요를 확인할 수 있습니다. 개발자 가이드와 API 참조를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수도 있습니다. +--- + +# Table 이벤트 개요 {#table-events-overview} + +Pivot API의 [`getTable`](api/methods/gettable-method.md) 메서드를 사용하면 Pivot 내부의 기본 Table 위젯 인스턴스에 접근하고 다음 Table 이벤트를 실행할 수 있습니다: + +| 이름 | 설명 | +| ------------------------------------------------- | ----------------------------------------------- | +| [](api/table/close-row.md) | @getshort(../table/close-row.md) | +| [](api/table/export.md) | @getshort(../table/export.md) | +| [](api/table/filter-rows.md) | @getshort(../table/filter-rows.md) | +| [](api/table/open-row.md) | @getshort(../table/open-row.md) | diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/table/close-row.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/close-row.md new file mode 100644 index 0000000..8b2f409 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/close-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: close-row +title: close-row +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 close-row 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판도 다운로드할 수 있습니다 +--- + +# close-row + +### 설명 {#description} + +@short: 행을 닫을(축소할) 때 발생합니다 + +Table 이벤트를 트리거하려면 [`getTable`](api/methods/gettable-method.md) 메서드를 통해 Pivot 내부의 기본 Table 위젯 인스턴스에 접근해야 합니다. 트리 모드는 [`tableShape`](api/config/tableshape-property.md) 속성을 통해 활성화해야 합니다. + +### 사용법 {#usage} + +```jsx {} +"close-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### 매개변수 {#parameters} + +액션의 callback은 다음 매개변수를 포함하는 객체를 받습니다: + +- `id` - (필수) 중첩 행을 가진 행의 id +- `nested` - (선택) **true**로 설정하면 중첩된 모든 항목이 축소됩니다 + +:::note +`id`가 0으로 설정되고 `nested`가 **true**로 설정되면 테이블의 모든 행이 축소됩니다 +::: + +### 예제 {#example} + +아래 스니펫은 버튼 클릭으로 모든 행을 열거나 닫는 방법을 보여줍니다: + + + +**관련 문서**: +- [`getTable`](api/methods/gettable-method.md) +- [모든 행 펼치기/접기](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/table/export.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/export.md new file mode 100644 index 0000000..3ca351e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/export.md @@ -0,0 +1,109 @@ +--- +sidebar_label: export +title: export +description: DHTMLX JavaScript Pivot 라이브러리의 export 이벤트에 대해 알아보실 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 직접 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드하실 수 있습니다 +--- + +# export + +### 설명 {#description} + +@short: 데이터를 내보낼 때 발생합니다 + +Table 이벤트를 트리거하려면 [`getTable`](api/methods/gettable-method.md) 메서드를 통해 Pivot 내부의 Table 인스턴스에 접근해야 합니다. + +### 사용법 {#usage} + +```jsx +"export": ({ + options: { + format: "csv" | "xlsx", + fileName?: string, + header?: boolean, + footer?: boolean, + download?: boolean, + + /* XLSX 설정*/ + styles?: boolean | { + header?: { + fontWeight?: "bold", + color?: string, + background?: string, + align?: "left"|"right"|"center", + borderBottom?: string, + borderRight?: string, + } + lastHeaderCell?: { /* header와 동일 */ }, + cell?: { /* header와 동일 */ }; + firstFooterCell?: { /* header와 동일 */ }, + footer?: {/* header와 동일 */}, + } + cellTemplate?: (value: any, row: any, column: object ) + => string | null, + headerCellTemplate?: (text: string, cell: object, column: object, type: "header"| "footer") + => string | null, + cellStyle?: (value: any, row: any, column: object) + => { format: string; align: "left"|"right"|"center" } | null, + headerCellStyle?: (text: string, cell: object, column: object, type: "header"| "footer") + => { format: string; align: "left"|"right"|"center" } | null, + sheetName?: string, + + /* CSV 설정 */ + rows: string, + cols: string, + }, + result?: any, +}) => boolean|void; +``` + +Table 위젯의 `export` 액션에는 필요에 따라 구성할 수 있는 다음과 같은 파라미터가 있습니다: + +- `options` - 내보내기 옵션이 담긴 객체입니다. 옵션은 형식 유형에 따라 다릅니다 +- `result` - 내보낸 Excel 또는 CSV 데이터의 결과값입니다 (일반적으로 `download` 옵션에 따라 Blob 또는 파일 형태입니다) + + **두 형식 모두에 적용되는 공통 옵션 ("csv" 및 "xlsx")**: + + - `format` (string) - (선택) 내보내기 형식으로 "csv" 또는 "xlsx"를 지정할 수 있습니다 + - `fileName` (string) - (선택) 파일 이름입니다 (기본값: "data") + - `header` (boolean) - (선택) 헤더를 내보낼지 여부를 지정합니다 (기본값: **true**) + - `footer` (boolean) - (선택) 푸터를 내보낼지 여부를 지정합니다 (기본값: **true**) + - `download` (boolean) - (선택) 파일 다운로드 여부를 지정합니다. 기본값은 **true**입니다. **false**로 설정하면 파일이 다운로드되지 않으며, Excel 또는 CSV 데이터(Blob)는 `ev.result`로 접근할 수 있습니다 + + **"xlsx" 형식에 특화된 옵션**: + + - `sheetName` (string) - Excel 시트 이름입니다 (기본값: "data") + - `styles` (boolean 또는 object) - **false**로 설정하면 스타일 없이 그리드를 내보냅니다. 스타일 속성 해시를 사용하여 구성할 수 있습니다: + - `header` - 헤더 셀에 대한 다음 설정이 담긴 객체입니다: + - `fontWeight` (string) - (선택) "bold"로 설정할 수 있으며, 설정하지 않으면 기본 폰트 두께가 적용됩니다 + - `color` (string) - (선택) 헤더의 텍스트 색상입니다 + - `background` (string) - (선택) 헤더의 배경 색상입니다 + - `align` - (선택) "left"|"right"|"center" 중 하나로 설정할 수 있는 텍스트 정렬입니다. 설정하지 않으면 Excel에서 설정된 정렬이 적용됩니다 + - `borderBottom` (string) - (선택) 하단 테두리 스타일입니다 + - `borderRight` (string) - (선택) 우측 테두리 스타일입니다 (예: *borderRight: "0.5px solid #dfdfdf"*) + - `lastHeaderCell` - 헤더 셀의 마지막 행에 대한 스타일 속성입니다. *header*와 동일한 속성을 사용합니다 + - `cell` - 본문 셀에 대한 스타일 속성입니다. *header*와 동일한 속성을 사용합니다 + - `firstFooterCell` - 푸터 셀의 첫 번째 행에 대한 스타일 속성입니다. *header*와 동일한 속성을 사용합니다 + - `footer` - 푸터 셀에 대한 스타일 속성입니다. *header*와 동일한 속성을 사용합니다 + - `cellTemplate` - 각 셀의 내보내기 값을 커스터마이즈하는 함수입니다. value, row, column 객체를 파라미터로 받아 내보낼 커스텀 값을 반환합니다 + - `headerCellTemplate` - 내보내기 시 헤더 또는 푸터 셀의 값을 커스터마이즈하는 함수입니다. text, 헤더 셀 객체, column 객체, 셀 유형("header" 또는 "footer")을 인수로 받아 내보낼 헤더/푸터 값을 수정할 수 있습니다 + - `cellStyle` - 내보내기 시 개별 셀의 스타일과 형식을 커스터마이즈할 수 있는 함수입니다. value, row, column 객체를 파라미터로 받아 스타일 속성(예: 정렬 또는 형식)이 담긴 객체를 반환해야 합니다 + - `headerCellStyle` - `cellStyle`과 유사하지만 헤더 및 푸터 셀에 특화된 함수입니다. text, 헤더 셀 객체, column 객체, 유형("header" 또는 "footer")을 받아 스타일 속성을 반환합니다 + :::note + 기본적으로 "xlsx" 형식의 경우 날짜 및 숫자 필드는 기본 형식 또는 [`fields`](api/config/fields-property.md) 속성을 통해 정의된 형식의 원시 값으로 내보내집니다. 단, 필드에 템플릿이 정의된 경우([`tableShape`](api/config/tableshape-property.md) 속성 참고) 해당 템플릿에서 정의된 렌더링 값으로 내보냅니다. 템플릿과 `format`이 모두 설정된 경우, 템플릿 설정이 형식 설정보다 우선 적용됩니다. + ::: + + **"csv" 형식에 특화된 옵션**: + + - `rows` (string) - (선택) 행 구분자입니다 (기본값: "\n") + - `cols` (string) - (선택) 열 구분자입니다 (기본값: "\t") + +## 예제 {#example} + +다음 스니펫에서 데이터 내보내기 방법을 확인할 수 있습니다: + + + +**관련 문서**: +- [`getTable`](api/methods/gettable-method.md) +- [데이터 내보내기](guides/exporting-data.md) +- [필드에 형식 적용하기](guides/working-with-data.md#applying-formats-to-fields) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/table/filter-rows.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/filter-rows.md new file mode 100644 index 0000000..40dcf58 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/filter-rows.md @@ -0,0 +1,35 @@ +--- +sidebar_label: filter-rows +title: filter-rows +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 filter-rows 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 사용해 보세요. DHTMLX Pivot 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# filter-rows + +### 설명 {#description} + +@short: 데이터 필터링 시 발생합니다 + +Table 이벤트를 발생시키려면 [`getTable`](api/methods/gettable-method.md) 메서드를 통해 Pivot 내부의 Table 인스턴스에 접근해야 합니다. + +### 사용법 {#usage} + +```jsx {} +"filter-rows": ({ + filter?: any +}) => boolean|void; +``` + +### 매개변수 {#parameters} + +액션의 callback은 다음 매개변수를 가진 객체를 받습니다: + +- `filter` - (선택 사항) 데이터 배열의 각 항목을 받아 각 항목에 대해 **true** 또는 **false**를 반환하는 필터링 함수 + +### 예제 {#example} + +아래 코드 조각은 입력값으로 테이블 본문의 집계된(표시되는) 데이터를 필터링하는 방법을 보여줍니다: + + + +**관련 글**: [`getTable`](api/methods/gettable-method.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/api/table/open-row.md b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/open-row.md new file mode 100644 index 0000000..2f5766c --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/api/table/open-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: open-row +title: open-row +description: DHTMLX JavaScript Pivot 라이브러리의 문서에서 open-row 이벤트에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# open-row + +### 설명 {#description} + +@short: 행을 열 때(펼칠 때) 발생합니다 + +Table 이벤트를 트리거하려면 [`getTable`](api/methods/gettable-method.md) 메서드를 사용하여 Pivot 내부의 Table 인스턴스에 접근해야 합니다. 트리 모드는 [`tableShape`](api/config/tableshape-property.md) 속성을 통해 활성화해야 합니다. + +### 사용법 {#usage} + +```jsx {} +"open-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### 매개변수 {#parameters} + +액션의 callback은 다음 매개변수를 포함하는 객체를 받습니다: + +- `id` - (필수) 중첩 행을 가진 행의 id +- `nested` - (선택) **true**로 설정하면 모든 중첩 항목이 펼쳐집니다 + +:::note +`id`가 0으로 설정되고 `nested`가 **true**이면 테이블의 모든 행이 펼쳐집니다 +::: + +### 예제 {#example} + +아래 코드 조각은 버튼 클릭으로 모든 행을 열거나 닫는 방법을 보여줍니다: + + + +**관련 아티클**: +- [`getTable`](api/methods/gettable-method.md) +- [모든 행 펼치기/접기](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/add_remove.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/add_remove.png new file mode 100644 index 0000000..81dcb52 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/add_remove.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/apply_filter.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/apply_filter.png new file mode 100644 index 0000000..53905a7 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/apply_filter.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/config_panel.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/config_panel.png new file mode 100644 index 0000000..41b7568 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/config_panel.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/filter.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/filter.png new file mode 100644 index 0000000..b4b1599 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/filter.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/filter_applied.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/filter_applied.png new file mode 100644 index 0000000..9ed7479 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/filter_applied.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/operations.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/operations.png new file mode 100644 index 0000000..80f6f79 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/operations.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/pivot-main.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/pivot-main.png new file mode 100644 index 0000000..5eaa953 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/pivot-main.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/priority.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/priority.png new file mode 100644 index 0000000..a827e01 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/priority.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/table.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/table.png new file mode 100644 index 0000000..f0fb3a9 Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/table.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/assets/trial_pivot.png b/i18n/ko/docusaurus-plugin-content-docs/current/assets/trial_pivot.png new file mode 100644 index 0000000..f2e21cf Binary files /dev/null and b/i18n/ko/docusaurus-plugin-content-docs/current/assets/trial_pivot.png differ diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/configuration.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/configuration.md new file mode 100644 index 0000000..fd4fa1e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/configuration.md @@ -0,0 +1,740 @@ +--- +sidebar_label: 구성 +title: 구성 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 구성에 대해 학습할 수 있습니다. 개발자 가이드와 API 레퍼런스를 탐색하고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot의 무료 30일 평가판을 다운로드하세요. +--- + +# 구성 {#configuration} + +다음 API를 통해 Pivot 테이블과 구성 패널을 설정합니다: + +- [`config`](api/config/config-property.md) — Pivot 테이블의 구조와 데이터 집계 방식을 정의합니다 +- [`render-table`](api/events/render-table-event.md) — 테이블 구성을 런타임에 변경합니다 +- [`tableShape`](api/config/tableshape-property.md) — Pivot 테이블의 외관을 설정합니다 +- [`columnShape`](api/config/columnshape-property.md) — 열의 외관과 동작을 설정합니다 +- [`headerShape`](api/config/headershape-property.md) — 헤더의 외관과 동작을 설정합니다 +- [`configPanel`](api/config/configpanel-property.md) — 구성 패널의 표시 여부를 제어합니다 +- [`setLocale`](api/methods/setlocale-method.md) — 로케일을 적용합니다([지역화](guides/localization.md) 참조) +- [`data`](api/config/data-property.md), [`fields`](api/config/fields-property.md) — 데이터와 필드 메타데이터를 불러옵니다 +- [`predicates`](api/config/predicates-property.md) — 집계 전에 데이터를 전처리합니다 +- [`methods`](api/config/methods-property.md) — 사용자 정의 집계 메서드를 정의합니다 +- [`limits`](api/config/limits-property.md) — 최종 데이터셋의 행과 열 수를 제한합니다 + +데이터 작업에 대한 자세한 내용은 [데이터 작업](guides/working-with-data.md)을 참조하세요. + +다음 Pivot 테이블 요소를 구성할 수 있습니다: + +- 열과 행 +- 헤더와 푸터 +- 셀 +- 테이블 크기 + +## 테이블 크기 조정 {#resizing-the-table} + +[`tableShape`](api/config/tableshape-property.md) 속성을 사용하여 행, 열, 헤더, 푸터의 크기를 변경합니다. + +다음 코드 스니펫은 기본 크기를 보여줍니다: + +~~~jsx +const sizes = { + rowHeight: 34, + headerHeight: 30, + footerHeight: 30, + columnWidth: 150 +}; +~~~ + +다음 코드 스니펫은 기본 크기를 재정의합니다: + +~~~jsx {4-11} +const table = new pivot.Pivot("#root", { + fields, + data, + tableShape: { + sizes: { + rowHeight: 44, + headerHeight: 60, + footerHeight: 30, + columnWidth: 170 + } + }, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +:::info +특정 열의 너비를 설정하려면 [`columnShape`](api/config/columnshape-property.md) 속성의 `width` 파라미터를 사용하세요. +::: + +## 열 너비를 콘텐츠에 자동 맞춤 {#autosize-columns-to-content} + +[`columnShape`](api/config/columnshape-property.md) 속성의 `autoWidth` 파라미터를 사용하면 열 너비를 자동으로 계산합니다. `autoWidth`의 모든 하위 파라미터는 선택 사항이며, 전체 설명은 [`columnShape`](api/config/columnshape-property.md) 레퍼런스를 참조하세요. + +`autoWidth` 객체는 다음 파라미터를 받습니다: + +- `columns` — 자동 계산 너비를 적용할 필드를 선택하는 객체 +- `auto` — 너비를 헤더, 셀 콘텐츠, 또는 둘 다에 맞춥니다 +- `maxRows` — 열 크기를 감지하기 위해 분석할 데이터 행 수(기본값: 20) +- `firstOnly` — `true`(기본값)이면 각 필드를 한 번만 분석합니다. 동일한 필드 기반의 여러 열(예: `count`와 `sum`을 사용하는 `oil`)이 있을 경우, 첫 번째 열만 분석하고 나머지 열은 해당 너비를 상속합니다 + +다음 코드 스니펫은 네 개의 필드에 `autoWidth`를 활성화하고, `firstOnly`를 비활성화하여 각 열이 개별적으로 측정되도록 합니다: + +~~~jsx {18-30} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + autoWidth: { + // 이 필드들의 열 너비를 계산합니다 + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + // 모든 필드를 분석합니다 + firstOnly: false + } + } +}); +~~~ + +## 셀에 템플릿 적용 {#applying-templates-to-cells} + +### tableShape를 통해 템플릿 추가 {#add-templates-via-tableshape} + +[`tableShape`](api/config/tableshape-property.md) 속성의 `templates` 파라미터를 사용하여 함수를 통해 셀 값을 렌더링합니다. 각 키는 필드 ID이고 각 값은 문자열을 반환하는 함수입니다. 지정된 필드를 기반으로 하는 모든 열에 템플릿이 적용됩니다. + +아래 예제는 `state` 셀에 템플릿을 적용하여 주의 전체 이름과 약자를 함께 표시합니다: + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", + // 다른 값들 +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // "state" 셀의 값을 커스터마이즈합니다 + state: v => v + ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // 다른 값들 + ], + }, + fields, +}); +~~~ + +### template 헬퍼를 통해 템플릿 추가 {#adding-a-template-via-the-template-helper} + +본문 셀에 HTML 콘텐츠를 삽입하려면 [`pivot.template`](api/helpers/template.md) 헬퍼를 사용하여 결과를 열 객체의 `cell` 속성에 할당합니다. [`api.intercept`](api/internal/intercept-method.md) 메서드로 [`render-table`](api/events/render-table-event.md) 이벤트를 가로채어 테이블이 렌더링되기 직전에 템플릿을 적용합니다. + +아래 예제는 필드(`id`, `user_score`)에 따라 본문 셀에 아이콘(별 또는 깃발)을 추가합니다: + +~~~js +function cellTemplate(value, method, row, column) { + const field = column.fields ? column.fields[row.$level] : column.field; + + if (field === "id") { + return idTemplate(value); + } + + if (field === "user_score") { + return scoreTemplate(value); + } + + return value; +} + +function idTemplate(value) { + const name = value?.toString().split("-")[0]; + return ` ${value}`; +} + +function scoreTemplate(value) { + return ` ${value}`; +} + +widget.api.intercept("render-table", ({ config: tableConfig }) => { + tableConfig.columns = tableConfig.columns.map((c) => { + if (c.area === "rows") { + // "rows" 영역 열의 셀에 템플릿을 적용합니다 + c.cell = pivot.template(({ value, method, row, column }) => cellTemplate(value, method, row, column)); + } + return c; + }); +}); +~~~ + +## 헤더에 템플릿 적용 {#applying-templates-to-headers} + +### headerShape를 통해 템플릿 추가 {#add-templates-via-headershape} + +헤더의 텍스트 형식을 제어하려면 [`headerShape`](api/config/headershape-property.md) 속성의 `template` 파라미터를 사용합니다. 이 파라미터는 다음 역할을 하는 함수입니다: + +- 필드 레이블, ID, 서브레이블(메서드 이름, 있는 경우)을 받습니다 +- 처리된 값을 반환합니다 + +기본 템플릿은 다음과 같습니다: + +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +사용자 정의 템플릿이 없으면 `values` 영역 필드는 레이블과 메서드를 표시하고(예: `Oil(count)`), 다른 영역 필드는 `label` 값을 표시합니다. [`predicates`](api/config/predicates-property.md) 템플릿은 `headerShape` 템플릿을 재정의합니다. + +아래 예제는 헤더 텍스트를 소문자로 변환하여 `profit (sum)`과 같은 레이블을 생성합니다: + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // 헤더 텍스트에 대한 사용자 정의 템플릿 + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // 다른 값들 + ], + }, + fields, +}); +~~~ + +### template 헬퍼를 통해 템플릿 추가 {#add-templates-via-the-template-helper} + +헤더 셀에 HTML 콘텐츠를 삽입하려면 [`pivot.template`](api/helpers/template.md) 헬퍼를 사용하여 결과를 헤더 셀 객체의 `cell` 속성에 할당합니다. [`api.intercept`](api/internal/intercept-method.md) 메서드로 [`render-table`](api/events/render-table-event.md) 이벤트를 가로채어 테이블이 렌더링되기 직전에 템플릿을 적용합니다. + +아래 예제는 다음에 아이콘을 추가합니다: + +- 필드 이름에 따른 헤더 레이블(예: `id`에는 지구 아이콘) +- 셀 값에 따른 열 헤더(`status` 값에 따른 색상 화살표 표시기) + +~~~jsx +function rowsHeaderTemplate(value, field) { + let icon = ""; + if (field === "id") icon = ""; + if (field === "user_score") icon = ""; + return `${value} ${icon}`; +} + +function statusTemplate(value) { + let icon = ""; + if (value === "Up") icon = ""; + if (value === "Down") icon = ""; + return `${value} ${icon}`; +} + +widget.api.intercept("render-table", ({ config: tableConfig }) => { + tableConfig.columns = tableConfig.columns.map((c) => { + if (c.area === "rows") { + // "rows" 영역 열의 첫 번째 헤더 행에 템플릿을 적용합니다 + c.header[0].cell = pivot.template(({ value, field }) => rowsHeaderTemplate(value, field)); + } else { + // "status" 필드의 값을 표시하는 헤더 셀 + const headerCell = c.header.find((h) => h.field === "status"); + if (headerCell) { + headerCell.cell = pivot.template(({ value }) => statusTemplate(value)); + } + } + return c; + }); +}); +~~~ + +## 열 축소 활성화 {#make-columns-collapsible} + +공유 헤더 아래의 열을 사용자가 축소하고 펼칠 수 있도록 하려면 [`headerShape`](api/config/headershape-property.md) 속성의 `collapsible` 파라미터를 `true`로 설정합니다. + +다음 코드 스니펫은 헤더 열을 축소 가능하도록 활성화합니다: + +~~~jsx {4-6} +const table = new pivot.Pivot("#root", { + fields, + data, + headerShape: { + collapsible: true, + }, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## 열 고정 {#freezing-columns} + +나머지 테이블이 스크롤될 때 왼쪽 또는 오른쪽 열이 표시되도록 고정합니다. [`tableShape`](api/config/tableshape-property.md) 속성의 `split` 파라미터를 사용하여 `left` 또는 `right`를 `true`로 설정합니다. + +### 왼쪽에 열 고정 {#freeze-columns-on-the-left} + +`split.left`가 `true`이면, 고정된 열 수는 [`config`](api/config/config-property.md) 속성의 `rows` 필드 수와 같습니다. 트리 모드에서는 `rows` 필드 수에 관계없이 열이 하나만 고정됩니다. + +다음 코드 스니펫은 왼쪽에 열 하나를 고정합니다(`rows` 필드가 하나 정의된 경우): + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + split: {left: true } + } +}); +~~~ + +사용자 정의 분할 수를 설정하려면 [`render-table`](api/events/render-table-event.md) 이벤트를 수신하여 `tableConfig.split`을 재정의합니다. colspan이 있는 열은 분할하지 마세요. + +다음 코드 스니펫은 모든 `rows` 열과 `values` 필드 수의 두 배만큼 왼쪽에 고정합니다: + +~~~jsx {19-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + { + field: "oil", + method: "sum" + }, + { + field: "oil", + method: "count" + } + ] + } +}); +table.api.on("render-table", ({ config: tableConfig }) => { + const { config } = table.api.getState(); + + tableConfig.split = { + left: config.rows.length + config.values.length * 2 + }; +}); +~~~ + +### 오른쪽에 열 고정 {#freezing-columns-on-the-right} + +`split.right`를 `true`로 설정하면 합계 열이 오른쪽에 고정됩니다. + +다음 코드 스니펫은 오른쪽에 합계 열을 고정합니다: + +~~~jsx {4-7} +const widget = new pivot.Pivot("#pivot", { + fields, + data: dataset, + tableShape:{ + split: {right: true}, + totalColumn: true, + }, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +오른쪽에 사용자 정의 수의 열을 고정하려면 [`render-table`](api/events/render-table-event.md) 이벤트를 수신하여 `tableConfig.split`을 재정의합니다. colspan이 있는 열은 분할하지 마세요. + +다음 코드 스니펫은 `values` 필드 수만큼 오른쪽에 열을 고정합니다: + +~~~jsx {20-25} +const widget = new pivot.Pivot("#pivot", { + fields, + data: dataset, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); + +widget.api.on("render-table", ({ config: tableConfig }) => { + const { config } = widget.api.getState(); + tableConfig.split = { + right: config.values.length, + } +}) +~~~ + +## 열 정렬 {#sort-in-columns} + +UI에서의 정렬은 기본적으로 활성화되어 있으며, 사용자가 열 헤더를 클릭하면 정렬됩니다. 비활성화하려면 [`columnShape`](api/config/columnshape-property.md) 속성의 `sort` 파라미터를 `false`로 설정합니다. + +다음 코드 스니펫은 UI 정렬을 비활성화합니다: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +기본 정렬, 사용자 정의 비교자, 런타임 업데이트에 대한 자세한 내용은 [데이터 정렬](guides/working-with-data.md#sorting-data)을 참조하세요. + +## 트리 모드 활성화 {#enabling-the-tree-mode} + +트리 모드는 확장 가능한 행으로 데이터를 계층적으로 표시합니다. [`tableShape`](api/config/tableshape-property.md) 속성의 `tree` 파라미터를 `true`(기본값 `false`)로 설정합니다. [`config`](api/config/config-property.md)의 `rows` 배열에서 첫 번째 필드가 상위 행이 됩니다. + +다음 코드 스니펫은 `studio`를 상위로, `genre`를 중첩 행으로 하는 트리 모드를 활성화합니다: + +~~~jsx {3} +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true + }, + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "max" + } + ] + } +}); +~~~ + +## 모든 행 펼치기 또는 축소하기 {#expandingcollapsing-all-rows} + +모든 행을 프로그래밍 방식으로 펼치거나 축소하려면 [`tableShape`](api/config/tableshape-property.md) 속성을 통해 트리 모드를 활성화합니다. 그런 다음 [`getTable`](api/methods/gettable-method.md) 메서드로 Table 위젯 인스턴스에 접근하고, Table의 `api.exec` 메서드를 통해 [`open-row`](api/table/open-row.md) 또는 [`close-row`](api/table/close-row.md) 이벤트를 트리거합니다. + +아래 예제는 트리 모드에서 모든 분기를 펼치거나 축소하는 "모두 열기"와 "모두 닫기" 버튼을 렌더링합니다: + +~~~jsx +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true + }, + fields, + data: dataset, + config: { + rows: ["type", "studio"], + columns: [], + values: [ + { + field: "score", + method: "max" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + }, + { + field: "episodes", + method: "count" + } + ] + } +}); + +const api = table.api; +const tableInstance = api.getTable(); +// 렌더링 시 모든 테이블 분기를 닫힌 상태로 유지합니다 +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // 테이블 렌더링을 방지하려면 여기서 false를 반환합니다 + // return false; +}); + +function openAll() { + tableInstance.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableInstance.exec("close-row", { id: 0, nested: true }); +} + +const openAllButton = document.createElement("button"); +openAllButton.addEventListener("click", openAll); +openAllButton.textContent = "Open all"; + +const closeAllButton = document.createElement("button"); +closeAllButton.addEventListener("click", closeAll); +closeAllButton.textContent = "Close all"; + +document.body.appendChild(openAllButton); +document.body.appendChild(closeAllButton); +~~~ + +## 헤더 텍스트 방향 변경 {#change-header-text-orientation} + +헤더 텍스트를 가로에서 세로로 회전하려면 [`headerShape`](api/config/headershape-property.md) 속성의 `vertical` 파라미터를 `true`로 설정합니다. + +다음 코드 스니펫은 헤더 텍스트를 세로로 렌더링합니다: + +~~~jsx {4-6} +const table = new pivot.Pivot("#root", { + fields, + data, + headerShape: { + vertical: true + }, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## 구성 패널 표시 여부 제어 {#controlling-visibility-of-configuration-panel} + +구성 패널은 기본적으로 표시됩니다. 사용자는 **설정 숨기기** / **설정 표시** 버튼으로 패널을 토글할 수 있습니다. [`configPanel`](api/config/configpanel-property.md) 속성, [`show-config-panel`](api/events/show-config-panel-event.md) 이벤트, 또는 [`showConfigPanel`](api/methods/showconfigpanel-method.md) 메서드를 통해 패널을 프로그래밍 방식으로 제어합니다. + +### 구성 패널 숨기기 {#hide-the-configuration-panel} + +초기화 시 패널을 숨기려면 [`configPanel`](api/config/configpanel-property.md) 속성을 `false`로 설정합니다. + +다음 코드 스니펫은 패널이 숨겨진 상태로 Pivot을 초기화합니다: + +~~~jsx +// 초기화 시 구성 패널이 숨겨집니다 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + configPanel: false, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +런타임에 패널을 토글하려면 [`api.exec`](api/internal/exec-method.md) 메서드로 [`show-config-panel`](api/events/show-config-panel-event.md) 이벤트를 트리거하고 `mode` 파라미터를 `false`로 설정합니다. + +다음 코드 스니펫은 초기화 후 패널을 숨깁니다: + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +// 구성 패널을 숨깁니다 +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +### 기본 토글 비활성화 {#disable-the-default-toggling} + +기본 토글 버튼을 완전히 차단하려면 [`api.intercept`](api/internal/intercept-method.md) 메서드로 [`show-config-panel`](api/events/show-config-panel-event.md) 이벤트를 가로채고 `false`를 반환합니다. + +다음 코드 스니펫은 토글 버튼을 비활성화합니다: + +~~~jsx {20-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.intercept("show-config-panel", () => { + return false; +}); +~~~ + +대안 API로는 [`showConfigPanel`](api/methods/showconfigpanel-method.md) 메서드를 사용합니다. + +### 패널에서 필드 작업 {#actions-with-fields-in-the-panel} + +구성 패널은 다음 필드 작업을 지원합니다: + +- [`add-field`](api/events/add-field-event.md) — 영역에 필드를 추가합니다 +- [`delete-field`](api/events/delete-field-event.md) — 영역에서 필드를 제거합니다 +- [`update-field`](api/events/update-field-event.md) — 필드의 메서드 또는 설정을 업데이트합니다 +- [`move-field`](api/events/move-field-event.md) — 영역 내 필드의 순서를 변경합니다 + +**관련 샘플**: +- [Pivot 2. 테이블 및 헤더 셀에 텍스트 템플릿 추가](https://snippet.dhtmlx.com/n9ylp6b2) +- [Pivot 2. 사용자 정의 고정(fixed) 열 (원하는 수)](https://snippet.dhtmlx.com/53erlmgp) +- [Pivot 2. 모든 행 펼치기 및 축소하기](https://snippet.dhtmlx.com/i4mi6ejn) +- [Pivot 2. 왼쪽 및 오른쪽에 고정(fixed) 열](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. 정렬](https://snippet.dhtmlx.com/j7vtief6) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/exporting-data.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/exporting-data.md new file mode 100644 index 0000000..06407b9 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/exporting-data.md @@ -0,0 +1,45 @@ +--- +sidebar_label: 데이터 내보내기 +title: 데이터 내보내기 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 데이터를 내보내는 방법을 살펴볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 참고하고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# 데이터 내보내기 {#exporting-data} + +Pivot은 내부 Table 위젯을 통해 테이블 데이터를 XLSX 또는 CSV 형식으로 내보냅니다. [`getTable`](api/methods/gettable-method.md) 메서드로 Table 인스턴스에 접근한 후, Table의 [`api.exec`](api/internal/exec-method.md) 메서드로 [`export`](api/table/export.md) 이벤트를 실행합니다. + +아래 예제는 Table 인스턴스에 접근하여 CSV 및 XLSX 형식으로 `export` 이벤트를 실행하는 방법을 보여줍니다: + +~~~jsx +const widget = new pivot.Pivot("#root", { /* settings */ }); + +widget.getTable().exec("export", { + options: { + format: "csv", + cols: ";" + } +}); + +widget.getTable().exec("export", { + options: { + format: "xlsx", + fileName: "My Report", + sheetName: "Quarter 1" + } +}); +~~~ + +:::tip +[`getTable`](api/methods/gettable-method.md) 메서드는 선택적 `wait` boolean 파라미터를 받습니다. `true`를 전달하면 Table API가 사용 가능해질 때 resolve되는 promise를 반환합니다. Pivot 초기화 중에 Table API가 준비되어야 할 때 유용합니다. +::: + +## 예제 {#example} + +아래 스니펫은 데이터를 내보내는 방법을 보여줍니다: + + + +**관련 문서**: + +- [날짜 형식 지정](guides/localization.md#date-formatting) +- [`export`](api/table/export.md) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/initialization.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/initialization.md new file mode 100644 index 0000000..e1109a1 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/initialization.md @@ -0,0 +1,86 @@ +--- +sidebar_label: 초기화 +title: 초기화 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 초기화에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# 초기화 {#initialization} + +이 가이드는 페이지에 Pivot을 생성하고 애플리케이션에 Pivot 테이블 기능을 추가하는 방법을 설명합니다. 다음 단계를 따라 사용 가능한 컴포넌트를 준비하세요: + +1. [페이지에 Pivot 소스 파일 포함하기](#include-source-files). +2. [Pivot을 위한 컨테이너 생성하기](#create-a-container). +3. [생성자로 Pivot 초기화하기](#initialize-pivot). + +## 소스 파일 포함 {#include-source-files} + +Pivot 앱은 페이지에 두 개의 소스 파일이 필요합니다. 패키지 다운로드 방법은 [패키지 다운로드](how-to-start.md#step-1-downloading-and-installing-packages)를 참조하세요. + +다음 파일을 포함하세요: + +- *pivot.js* +- *pivot.css* + +소스 파일에 대한 올바른 상대 경로를 설정하세요: + +~~~html title="index.html" + + +~~~ + +## 컨테이너 생성 {#create-a-container} + +Pivot은 HTML 컨테이너 요소에 렌더링됩니다. 컨테이너를 추가하고 ID를 지정하세요. 예를 들어 *"root"*: + +~~~html title="index.html" +
+~~~ + +## Pivot 초기화 {#initialize-pivot} + +`pivot.Pivot` 생성자는 두 개의 매개변수를 받습니다: + +- HTML 컨테이너의 ID +- 구성 속성이 담긴 객체 + +다음 코드 스니펫은 초기 필드, 데이터, 구조를 포함한 Pivot 인스턴스를 *"root"* 컨테이너에 생성합니다: + +~~~jsx +// Pivot 생성 +const table = new pivot.Pivot("#root", { + // 구성 속성 + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +생성자는 Pivot 인스턴스를 반환합니다. 반환된 인스턴스에서 API 메서드를 호출하세요: + +- [`getTable`](api/methods/gettable-method.md) — 기반 Table 위젯 인스턴스에 접근합니다 +- [`setConfig`](api/methods/setconfig-method.md) — 현재 Pivot 구성을 업데이트합니다 +- [`setLocale`](api/methods/setlocale-method.md) — Pivot에 새 로케일을 적용합니다 +- [`showConfigPanel`](api/methods/showconfigpanel-method.md) — 구성 패널을 표시하거나 숨깁니다 + +## 구성 속성 {#configuration-properties} + +Pivot 생성자는 데이터, 레이아웃, 동작을 제어하는 구성 속성이 담긴 객체를 받습니다. + +:::info +Pivot을 구성하기 위한 전체 속성 목록은 [속성 개요](api/overview/properties-overview.md)를 참조하세요. +::: + +## 예제 {#example} + +아래 스니펫은 초기 데이터로 Pivot을 초기화합니다: + + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md new file mode 100644 index 0000000..30c198e --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md @@ -0,0 +1,325 @@ +--- +sidebar_label: Angular와의 통합 +title: Angular와의 통합 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 Angular와의 통합에 대해 알아볼 수 있습니다. 개발자 가이드와 API 참조를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# Angular와의 통합 {#integration-with-angular} + +:::tip +**Angular**의 기본 개념과 패턴에 익숙하다고 가정합니다. 복습이 필요하다면 [**Angular 문서**](https://v17.angular.io/docs)를 참조하세요. +::: + +DHTMLX Pivot은 일반 컴포넌트로서 **Angular**와 통합됩니다. 완전한 동작 예제는 [**GitHub의 Angular Pivot 데모**](https://github.com/DHTMLX/angular-pivot-demo)를 참조하세요. + +## 프로젝트 생성 {#create-a-project} + +:::info +시작하기 전에 [**Angular CLI**](https://v1.angular.io/cli)와 [**Node.js**](https://nodejs.org/en/)를 설치하세요. +::: + +다음 명령어로 *my-angular-pivot-app*이라는 새 Angular 프로젝트를 생성합니다: + +~~~bash +ng new my-angular-pivot-app +~~~ + +:::note +Angular CLI의 안내에 따라 서버 사이드 렌더링(SSR)과 정적 사이트 생성(SSG/Prerendering)을 비활성화하세요 — 이 가이드는 클라이언트 렌더링 앱을 기준으로 합니다. +::: + +명령어를 실행하면 필요한 모든 도구가 설치됩니다. 추가 명령어는 필요하지 않습니다. + +### 의존성 설치 {#install-dependencies} + +새 프로젝트 디렉토리로 이동합니다: + +~~~bash +cd my-angular-pivot-app +~~~ + +[**yarn**](https://yarnpkg.com/) 패키지 매니저로 의존성을 설치하고 개발 서버를 시작합니다: + +~~~bash +yarn +yarn start # 또는: yarn dev +~~~ + +앱이 로컬 포트(예: `http://localhost:3000`)에서 실행됩니다. + +## Pivot 생성 {#create-pivot} + +프로젝트에 Pivot 패키지를 추가한 후, Angular 컴포넌트로 Pivot을 감쌉니다. + +### 1단계. 패키지 설치 {#step-1-install-the-package} + +[**Pivot 체험판 패키지**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn)를 다운로드하고 README의 단계를 따르세요. Pivot 체험판 패키지는 30일간 유효합니다. + +### 2단계. 컴포넌트 생성 {#step-2-create-the-component} + +Pivot을 마운트하는 Angular 컴포넌트를 생성합니다. *src/app/* 아래에 *pivot* 폴더를 추가하고 *src/app/pivot/pivot.component.ts*를 생성합니다. 그런 다음 아래 단계를 따르세요: + +#### 소스 파일 가져오기 {#import-source-files} + +*src/app/pivot/pivot.component.ts*를 열고 Pivot 패키지를 가져옵니다. 가져오기 경로는 패키지 버전에 따라 다릅니다: + +- **PRO 버전** (로컬 폴더에서 설치): + +~~~jsx +import { Pivot } from 'dhx-pivot-package'; +~~~ + +- **체험판 버전**: + +~~~jsx +import { Pivot } from '@dhx/trial-pivot'; +~~~ + +이 튜토리얼은 Pivot 체험판을 사용합니다. + +#### 컨테이너 설정 및 Pivot 마운트 {#set-up-the-container-and-mount-pivot} + +페이지에 Pivot을 표시하려면 컴포넌트 템플릿에 컨테이너 요소를 정의한 후, 생성자를 사용하여 `ngOnInit` 훅에서 Pivot을 초기화합니다. `ngOnDestroy` 훅에서 Pivot을 소멸시킵니다. + +다음 코드 스니펫은 최소한의 Pivot Angular 컴포넌트를 정의합니다: + +~~~jsx {1,8,12-13,18-19} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation } from '@angular/core'; + +@Component({ + encapsulation: ViewEncapsulation.None, + selector: "pivot", // "app.component.ts" 파일에서 으로 사용되는 템플릿 이름 + styleUrls: ["./pivot.component.css"], // CSS 파일 포함 + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + // Pivot의 컨테이너 참조 + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + // Pivot 컴포넌트 초기화 + this._table = new Pivot(this.pivot_container.nativeElement, {}); + } + + ngOnDestroy(): void { + this._table.destructor(); // 언마운트 시 Pivot 소멸 + } +} +~~~ + +#### 스타일 추가 {#add-styles} + +Pivot을 올바르게 렌더링하려면 *src/app/pivot/pivot.component.css*를 생성하고 페이지와 Pivot 컨테이너에 대한 스타일을 작성합니다: + +~~~css title="pivot.component.css" +/* Pivot 스타일 가져오기 */ +@import "@dhx/trial-pivot/dist/pivot.css"; + +/* 초기 페이지 스타일 */ +html, +body { + margin: 0; + padding: 0; + height: 100%; +} + +/* Pivot 컨테이너 스타일 */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### 데이터 로드 {#load-data} + +Pivot에 데이터를 제공하려면 데이터셋을 준비합니다. *src/app/pivot/data.ts*를 생성하고 데이터와 필드 메타데이터를 내보냅니다: + +~~~jsx title="data.ts" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 다른 데이터 항목 + ]; + + const fields: any = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 다른 필드 + ]; + + return { dataset, fields }; +}; +~~~ + +*src/app/pivot/pivot.component.ts*를 열고 `getData`를 가져온 후 `ngOnInit()`에서 데이터셋을 적용합니다: + +~~~jsx {2,18,20-21} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { getData } from "./data"; // 데이터 가져오기 +import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation } from '@angular/core'; + +@Component({ + encapsulation: ViewEncapsulation.None, + selector: "pivot", + styleUrls: ["./pivot.component.css"], + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + const { dataset, fields } = getData(); // 데이터와 필드 메타데이터 가져오기 + this._table = new Pivot(this.pivot_container.nativeElement, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 다른 값 + ] + }, + // 다른 구성 속성 + }); + } + + ngOnDestroy(): void { + this._table.destructor(); + } +} +~~~ + +이제 컴포넌트를 사용할 준비가 되었습니다. 마운트 시 Pivot은 제공된 데이터로 렌더링됩니다. 구성 속성의 전체 목록은 [Pivot API 문서](api/overview/properties-overview.md)를 참조하세요. + +#### 이벤트 처리 {#handle-events} + +Pivot에서의 사용자 동작은 구독할 수 있는 이벤트를 발생시킵니다. 이벤트의 전체 목록은 [이벤트 개요](api/overview/events-overview.md)를 참조하세요. + +다음 코드 스니펫은 사용자가 필터를 열 때 필드 ID를 로그에 출력하는 `open-filter` 이벤트 리스너를 `ngOnInit`에 추가합니다: + +~~~jsx {18-20} title="pivot.component.ts" +// ... +ngOnInit() { + const { dataset, fields } = getData(); + this._table = new Pivot(this.pivot_container.nativeElement, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 다른 값 + ] + } + }); + + this._table.api.on("open-filter", (ev) => { + console.log("The field id for which the filter is activated:", ev.id); + }); +} + +ngOnDestroy(): void { + this._table.destructor(); +} +~~~ + +### 3단계. 앱에 Pivot 추가 {#step-3-add-pivot-to-the-app} + +`PivotComponent`를 앱에 포함하려면 *src/app/app.component.ts*를 열고 기본 코드를 다음으로 교체합니다: + +~~~jsx {5} title="app.component.ts" +import { Component } from "@angular/core"; + +@Component({ + selector: "app-root", + template: `` // "pivot.component.ts" 파일에서 생성된 템플릿 +}) +export class AppComponent { + name = ""; +} +~~~ + +그런 다음 *src/app/app.module.ts*를 생성하고 `PivotComponent`를 등록합니다: + +~~~jsx {4-5,8} title="app.module.ts" +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; + +import { AppComponent } from "./app.component"; +import { PivotComponent } from "./pivot/pivot.component"; + +@NgModule({ + declarations: [AppComponent, PivotComponent], + imports: [BrowserModule], + bootstrap: [AppComponent] +}) +export class AppModule {} +~~~ + +마지막으로, *src/main.ts*를 열고 내용을 다음 부트스트랩 코드로 교체합니다: + +~~~jsx title="main.ts" +import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; +import { AppModule } from "./app/app.module"; +platformBrowserDynamic() + .bootstrapModule(AppModule) + .catch((err) => console.error(err)); +~~~ + +앱을 시작하면 Pivot이 페이지에 데이터를 렌더링하는 것을 확인할 수 있습니다. + +![Pivot 초기화](../assets/trial_pivot.png) + +이제 Pivot이 Angular와 통합되었습니다. 프로젝트 요구 사항에 맞게 구성을 커스터마이즈하세요. 최종 예제는 [**GitHub의 angular-pivot-demo**](https://github.com/DHTMLX/angular-pivot-demo)를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-react.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-react.md new file mode 100644 index 0000000..1ebe91c --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-react.md @@ -0,0 +1,289 @@ +--- +sidebar_label: React와의 통합 +title: React와의 통합 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 React와의 통합에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot 30일 무료 평가판을 다운로드하세요. +--- + +# React와의 통합 {#integration-with-react} + +:::tip +[**React**](https://react.dev)의 기본 개념과 패턴에 익숙하다고 가정합니다. 복습이 필요하다면 [**React 문서**](https://react.dev/learn)를 참고하세요. +::: + +DHTMLX Pivot은 일반 컴포넌트로 **React**와 통합됩니다. 완전한 동작 예제는 [**GitHub의 React Pivot 데모**](https://github.com/DHTMLX/react-pivot-demo)를 참고하세요. + +## 프로젝트 생성 {#create-a-project} + +:::info +시작하기 전에 [**Node.js**](https://nodejs.org/en/)를 설치하세요. [**Vite**](https://vite.dev/)는 선택 사항입니다. +::: + +*my-react-pivot-app*이라는 이름으로 기본 **React** 프로젝트(또는 Vite 기반 프로젝트)를 생성합니다. + +다음 명령어로 Create React App 프로젝트를 부트스트랩합니다: + +~~~bash +npx create-react-app my-react-pivot-app +~~~ + +### 의존성 설치 {#install-dependencies} + +새 프로젝트 디렉토리로 이동합니다: + +~~~bash +cd my-react-pivot-app +~~~ + +패키지 매니저로 의존성을 설치하고 개발 서버를 시작합니다: + +- [**yarn**](https://yarnpkg.com/) 사용 시: + +~~~bash +yarn +yarn start # 또는: yarn dev +~~~ + +- [**npm**](https://www.npmjs.com/) 사용 시: + +~~~bash +npm install +npm run dev +~~~ + +앱이 로컬 포트(예: `http://localhost:3000`)에서 실행됩니다. + +## Pivot 생성 {#create-pivot} + +프로젝트에 Pivot 패키지를 추가한 후 Pivot을 React 컴포넌트로 래핑합니다. + +### 1단계. 패키지 설치 {#step-1-install-the-package} + +[**Pivot 평가판 패키지**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn)를 다운로드하고 README의 단계를 따르세요. Pivot 평가판 패키지는 30일간 유효합니다. + +### 2단계. 컴포넌트 생성 {#step-2-create-the-component} + +Pivot을 마운트하는 React 컴포넌트를 생성합니다. *src/Pivot.jsx* 파일을 새로 추가합니다. + +#### 소스 파일 가져오기 {#import-source-files} + +*src/Pivot.jsx*를 열고 Pivot 소스 파일을 가져옵니다. 가져오기 경로는 패키지 에디션에 따라 다릅니다: + +- **PRO 버전** (로컬 폴더에서 설치): + +~~~jsx title="Pivot.jsx" +import { Pivot } from 'dhx-pivot-package'; +import 'dhx-pivot-package/dist/pivot.css'; +~~~ + +패키지에 최소화된 에셋이 포함된 경우 *pivot.css* 대신 *pivot.min.css*를 가져옵니다. + +- **평가판**: + +~~~jsx title="Pivot.jsx" +import { Pivot } from '@dhx/trial-pivot'; +import "@dhx/trial-pivot/dist/pivot.css"; +~~~ + +이 튜토리얼에서는 Pivot 평가판을 사용합니다. + +#### 컨테이너 설정 및 Pivot 마운트 {#set-up-the-container-and-mount-pivot} + +페이지에 Pivot을 표시하려면 컨테이너 `div`를 생성한 후 생성자를 사용하여 `useEffect` hook에서 Pivot을 초기화합니다. + +다음 코드 스니펫은 최소한의 Pivot React 컴포넌트를 정의합니다: + +~~~jsx {2,6,9-10} title="Pivot.jsx" +import { useEffect, useRef } from "react"; +import { Pivot } from "@dhx/trial-pivot"; +import "@dhx/trial-pivot/dist/pivot.css"; // Pivot 스타일 포함 + +export default function PivotComponent(props) { + let container = useRef(); // Pivot용 컨테이너 ref + + useEffect(() => { + // Pivot 컴포넌트 초기화 + const table = new Pivot(container.current, {}); + + return () => { + table.destructor(); // 언마운트 시 Pivot 제거 + }; + }, []); + + return
; +} +~~~ + +#### 스타일 추가 {#add-styles} + +Pivot을 올바르게 렌더링하려면 프로젝트의 메인 CSS 파일에 다음 스타일을 추가합니다: + +~~~css title="index.css" +/* 초기 페이지 스타일 */ +html, +body, +#root { + height: 100%; + padding: 0; + margin: 0; +} + +/* Pivot 컨테이너 스타일 */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### 데이터 로드 {#load-data} + +Pivot에 데이터를 공급하려면 데이터셋을 준비합니다. *src/data.js*를 생성하고 데이터와 필드 메타데이터를 내보냅니다: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 다른 데이터 항목 + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 다른 필드 + ]; + + return { dataset, fields }; +}; +~~~ + +*src/App.js*를 열고 데이터를 가져온 후 `` 컴포넌트에 props로 전달합니다: + +~~~jsx {2,5-6} title="App.js" +import Pivot from "./Pivot"; +import { getData } from "./data"; + +function App() { + const { fields, dataset } = getData(); + return ; +} + +export default App; +~~~ + +*src/Pivot.jsx*를 열고 props를 구조 분해하여 Pivot 설정 객체에 적용합니다: + +~~~jsx {5,10-11} title="Pivot.jsx" +import { useEffect, useRef } from "react"; +import { Pivot } from "@dhx/trial-pivot"; +import "@dhx/trial-pivot/dist/pivot.css"; + +export default function PivotComponent({ fields, dataset }) { + let container = useRef(); + + useEffect(() => { + const table = new Pivot(container.current, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 다른 값 + ] + }, + // 다른 설정 속성 + }); + + return () => { + table.destructor(); + } + }, []); + + return
; +} +~~~ + +이제 컴포넌트를 사용할 준비가 되었습니다. 마운트 시 Pivot은 제공된 데이터로 렌더링됩니다. 전체 설정 속성 목록은 [Pivot API 문서](api/overview/properties-overview.md)를 참고하세요. + +#### 이벤트 처리 {#handle-events} + +Pivot에서 발생하는 사용자 동작은 구독할 수 있는 이벤트를 발생시킵니다. 전체 이벤트 목록은 [이벤트 개요](api/overview/events-overview.md)를 참고하세요. + +다음 코드 스니펫은 사용자가 필터를 열 때 필드 ID를 로그에 기록하는 `open-filter` 이벤트 리스너를 `useEffect`에 추가합니다: + +~~~jsx {19-21} title="Pivot.jsx" +// ... +useEffect(() => { + const table = new Pivot(container.current, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 다른 값 + ] + }, + // 다른 설정 속성 + }); + + table.api.on("open-filter", (ev) => { + console.log("필터가 활성화된 필드 id:", ev.id); + }); + + return () => { + table.destructor(); + } +}, []); +// ... +~~~ + +앱을 시작하면 페이지에 Pivot이 데이터를 렌더링하는 것을 확인할 수 있습니다. + +![Pivot 초기화](../assets/trial_pivot.png) + +이제 Pivot이 React와 통합되었습니다. 프로젝트 요구 사항에 맞게 설정을 사용자 정의하세요. 최종 예제는 [**GitHub의 react-pivot-demo**](https://github.com/DHTMLX/react-pivot-demo)를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md new file mode 100644 index 0000000..0669523 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md @@ -0,0 +1,302 @@ +--- +sidebar_label: Svelte와의 통합 +title: Svelte와의 통합 +description: DHTMLX JavaScript Pivot 라이브러리의 문서에서 Svelte와의 통합에 대해 알아볼 수 있습니다. 개발자 가이드와 API 참조를 살펴보고, 코드 예제와 라이브 데모를 사용해 보고, DHTMLX Pivot의 무료 30일 평가판을 다운로드하세요. +--- + +# Svelte와의 통합 {#integration-with-svelte} + +:::tip +**Svelte**의 기본 개념과 패턴에 익숙하다고 가정합니다. 복습이 필요하다면 [**Svelte 문서**](https://svelte.dev/)를 참조하세요. +::: + +DHTMLX Pivot은 일반 컴포넌트로서 **Svelte**와 통합됩니다. 완전한 동작 예제는 [**GitHub의 Svelte Pivot 데모**](https://github.com/DHTMLX/svelte-pivot-demo)를 참조하세요. + +## 프로젝트 만들기 {#create-a-project} + +:::info +시작하기 전에 [**Node.js**](https://nodejs.org/en/)를 설치하세요. [**Vite**](https://vite.dev/)는 선택 사항입니다. +::: + +다음 명령어는 Vite 프로젝트 스캐폴딩 도구를 실행하고 Svelte 템플릿을 선택할 수 있게 해줍니다: + +~~~bash +npm create vite@latest +~~~ + +프로젝트 이름을 *my-svelte-pivot-app*으로 지정하세요. + +### 의존성 설치 {#install-dependencies} + +새 프로젝트 디렉토리로 이동하세요: + +~~~bash +cd my-svelte-pivot-app +~~~ + +패키지 매니저로 의존성을 설치하고 개발 서버를 시작하세요: + +- [**yarn**](https://yarnpkg.com/) 사용 시: + +~~~bash +yarn +yarn start # 또는: yarn dev +~~~ + +- [**npm**](https://www.npmjs.com/) 사용 시: + +~~~bash +npm install +npm run dev +~~~ + +앱은 로컬 포트(예: `http://localhost:3000`)에서 실행됩니다. + +## Pivot 만들기 {#create-pivot} + +프로젝트에 Pivot 패키지를 추가한 다음, Svelte 컴포넌트로 Pivot을 감싸세요. + +### 1단계. 패키지 설치 {#step-1-install-the-package} + +[**Pivot 체험판 패키지**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn)를 다운로드하고 README의 단계를 따르세요. Pivot 체험판 패키지는 30일 동안 유효합니다. + +### 2단계. 컴포넌트 만들기 {#step-2-create-the-component} + +Pivot을 마운트하는 Svelte 컴포넌트를 만드세요. 새 파일 *src/Pivot.svelte*를 추가하세요. + +#### 소스 파일 가져오기 {#import-source-files} + +*src/Pivot.svelte*를 열고 Pivot 소스 파일을 가져오세요. 가져오기 경로는 패키지 에디션에 따라 다릅니다: + +- **PRO 버전** (로컬 폴더에서 설치): + +~~~html title="Pivot.svelte" + +~~~ + +패키지가 최소화된 에셋을 포함하는 경우, *pivot.css* 대신 *pivot.min.css*를 가져오세요. + +- **체험판 버전**: + +~~~html title="Pivot.svelte" + +~~~ + +이 튜토리얼에서는 Pivot 체험판 버전을 사용합니다. + +#### 컨테이너 설정 및 Pivot 마운트 {#set-up-the-container-and-mount-pivot} + +페이지에 Pivot을 표시하려면 컨테이너 `div`를 추가한 다음, 생성자를 사용해 `onMount` 라이프사이클 훅에서 Pivot을 초기화하세요. `onDestroy` 훅에서 Pivot을 소멸시키세요. + +다음 코드 스니펫은 최소한의 Pivot Svelte 컴포넌트를 정의합니다: + +~~~html {3,6,10-11,19} title="Pivot.svelte" + + +
+~~~ + +#### 스타일 추가 {#add-styles} + +Pivot을 올바르게 렌더링하려면 프로젝트의 메인 CSS 파일에 다음 스타일을 추가하세요: + +~~~css title="main.css" +/* 초기 페이지 스타일 */ +html, +body, +#app { /* #app 루트 컨테이너 사용 */ + height: 100%; + padding: 0; + margin: 0; +} + +/* Pivot 컨테이너 스타일 */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### 데이터 로드 {#load-data} + +Pivot에 데이터를 제공하려면 데이터셋을 준비하세요. *src/data.js*를 만들고 데이터와 필드 메타데이터를 내보내세요: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 다른 데이터 항목 + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 다른 필드 + ]; + + return { dataset, fields }; +}; +~~~ + +*src/App.svelte*를 열고 데이터를 가져온 다음 새 `` 컴포넌트에 props로 전달하세요: + +~~~html {3,5,8} title="App.svelte" + + + +~~~ + +*src/Pivot.svelte*를 열고 `export let`으로 들어오는 props를 선언하고 Pivot 설정 객체에 적용하세요: + +~~~html {6-7,14-15} title="Pivot.svelte" + + +
+~~~ + +이제 컴포넌트를 사용할 준비가 되었습니다. 마운트 시 Pivot은 제공된 데이터로 렌더링됩니다. 전체 설정 속성 목록은 [Pivot API 문서](api/overview/properties-overview.md)를 참조하세요. + +#### 이벤트 처리 {#handle-events} + +Pivot에서의 사용자 동작은 구독할 수 있는 이벤트를 발생시킵니다. 전체 이벤트 목록은 [이벤트 개요](api/overview/events-overview.md)를 참조하세요. + +다음 코드 스니펫은 사용자가 필터를 열 때 필드 ID를 기록하는 `open-filter` 이벤트 리스너로 `onMount`를 확장합니다: + +~~~html {22-24} title="Pivot.svelte" + + +// ... +~~~ + +앱을 시작하면 Pivot이 페이지에 데이터를 렌더링하는 것을 확인할 수 있습니다. + +![Pivot 초기화](../assets/trial_pivot.png) + +이제 Pivot이 Svelte와 통합되었습니다. 프로젝트 요구사항에 맞게 설정을 커스터마이즈하세요. 최종 예제는 [**GitHub의 svelte-pivot-demo**](https://github.com/DHTMLX/svelte-pivot-demo)를 참조하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md new file mode 100644 index 0000000..34f50d9 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md @@ -0,0 +1,312 @@ +--- +sidebar_label: Vue와의 통합 +title: Vue와의 통합 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 Vue와의 통합에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수도 있습니다. +--- + +# Vue와의 통합 {#integration-with-vue} + +:::tip +[**Vue**](https://vuejs.org/)의 기본 개념과 패턴에 익숙하다고 가정합니다. 복습이 필요하다면 [**Vue 3 문서**](https://vuejs.org/guide/introduction.html#getting-started)를 참고하세요. +::: + +DHTMLX Pivot은 일반 컴포넌트로서 **Vue**와 통합됩니다. 완전한 작동 설정 예시는 [**GitHub의 Vue Pivot 데모**](https://github.com/DHTMLX/vue-pivot-demo)를 참고하세요. + +## 프로젝트 생성 {#create-a-project} + +:::info +시작하기 전에 [**Node.js**](https://nodejs.org/en/)를 설치하세요. +::: + +다음 명령어는 공식 **Vue** 프로젝트 스캐폴딩 도구를 실행합니다: + +~~~bash +npm create vue@latest +~~~ + +이 명령어는 `create-vue`를 설치하고 실행합니다. 자세한 내용은 [Vue.js 빠른 시작](https://vuejs.org/guide/quick-start.html#creating-a-vue-application)을 참고하세요. + +프로젝트 이름을 *my-vue-pivot-app*으로 지정하세요. + +### 의존성 설치 {#install-dependencies} + +새 프로젝트 디렉터리로 이동합니다: + +~~~bash +cd my-vue-pivot-app +~~~ + +패키지 매니저로 의존성을 설치하고 개발 서버를 시작합니다: + +- [**yarn**](https://yarnpkg.com/) 사용 시: + +~~~bash +yarn +yarn start # 또는: yarn dev +~~~ + +- [**npm**](https://www.npmjs.com/) 사용 시: + +~~~bash +npm install +npm run dev +~~~ + +앱은 로컬 포트(예: `http://localhost:3000`)에서 실행됩니다. + +## Pivot 생성 {#create-pivot} + +프로젝트에 Pivot 패키지를 추가한 다음 Pivot을 Vue 컴포넌트로 래핑합니다. + +### 1단계. 패키지 설치 {#step-1-install-the-package} + +[**Pivot 평가판 패키지**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn)를 다운로드하고 README의 단계를 따르세요. Pivot 평가판 패키지는 30일간 유효합니다. + +### 2단계. 컴포넌트 생성 {#step-2-create-the-component} + +Pivot을 마운트하는 Vue 컴포넌트를 생성합니다. *src/components/Pivot.vue* 파일을 새로 추가하세요. + +#### 소스 파일 가져오기 {#import-source-files} + +*src/components/Pivot.vue*를 열고 Pivot 소스 파일을 가져옵니다. 가져오기 경로는 패키지 에디션에 따라 다릅니다: + +- **PRO 버전** (로컬 폴더에서 설치한 경우): + +~~~html title="Pivot.vue" + +~~~ + +패키지가 압축된 에셋을 제공하는 경우 *pivot.css* 대신 *pivot.min.css*를 가져옵니다. + +- **평가판 버전**: + +~~~html title="Pivot.vue" + +~~~ + +이 튜토리얼에서는 Pivot 평가판을 사용합니다. + +#### 컨테이너 설정 및 Pivot 마운트 {#set-up-the-container-and-mount-pivot} + +페이지에 Pivot을 표시하려면 컨테이너 `div`를 추가한 다음 생성자를 사용하여 `mounted` 훅에서 Pivot을 초기화합니다. `unmounted` 훅에서 Pivot을 제거합니다. + +다음 코드 스니펫은 최소한의 Pivot Vue 컴포넌트를 정의합니다: + +~~~html {2,7-8,18} title="Pivot.vue" + + + +~~~ + +#### 스타일 추가 {#add-styles} + +Pivot을 올바르게 렌더링하려면 프로젝트의 메인 CSS 파일에 다음 스타일을 추가합니다: + +~~~css title="style.css" +/* 초기 페이지 스타일 */ +html, +body, +#app { /* #app 루트 컨테이너 사용 */ + height: 100%; + padding: 0; + margin: 0; +} + +/* Pivot 컨테이너 스타일 */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### 데이터 로드 {#load-data} + +Pivot에 데이터를 공급하려면 데이터셋을 준비합니다. *src/data.js*를 생성하고 데이터와 필드 메타데이터를 내보냅니다: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 다른 데이터 항목 + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 다른 필드 + ]; + + return { dataset, fields }; +}; +~~~ + +*src/App.vue*를 열고 데이터를 가져온 다음 `data()` 옵션을 통해 노출합니다. 그런 다음 값을 새 `` 컴포넌트에 props로 전달합니다: + +~~~html {3,7-13,18} title="App.vue" + + + +~~~ + +*src/components/Pivot.vue*를 열고 들어오는 props를 선언한 다음 Pivot 구성 객체에 적용합니다: + +~~~html {6,10-11} title="Pivot.vue" + + + +~~~ + +이제 컴포넌트를 사용할 준비가 되었습니다. 마운트 시 Pivot은 제공된 데이터로 렌더링됩니다. 구성 속성의 전체 목록은 [Pivot API 문서](api/overview/properties-overview.md)를 참고하세요. + +#### 이벤트 처리 {#handle-events} + +Pivot에서 사용자 동작이 발생하면 구독할 수 있는 이벤트가 발생합니다. 이벤트의 전체 목록은 [이벤트 개요](api/overview/events-overview.md)를 참고하세요. + +다음 코드 스니펫은 `mounted`를 `open-filter` 이벤트 리스너로 확장하여 사용자가 필터를 열 때 필드 ID를 로그에 기록합니다: + +~~~html {22-24} title="Pivot.vue" + + +// ... +~~~ + +앱을 시작하면 페이지에서 Pivot이 데이터를 렌더링하는 것을 확인할 수 있습니다. + +![Pivot 초기화](../assets/trial_pivot.png) + +이제 Pivot이 Vue와 통합되었습니다. 프로젝트 요구 사항에 맞게 구성을 사용자 정의하세요. 최종 예제는 [**GitHub의 vue-pivot-demo**](https://github.com/DHTMLX/vue-pivot-demo)를 참고하세요. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/loading-data.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/loading-data.md new file mode 100644 index 0000000..9eb37c3 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/loading-data.md @@ -0,0 +1,279 @@ +--- +sidebar_label: 데이터 로드 +title: 데이터 로드 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 데이터를 로드하는 방법을 살펴볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 참조하고, 코드 예제와 라이브 데모를 사용해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수도 있습니다. +--- + +# 데이터 로드 {#loading-data} + +Pivot은 [`data`](api/config/data-property.md) 속성을 통해 JSON 형식의 데이터를 받습니다. CSV 데이터는 JSON으로 변환한 후 사용할 수 있습니다. + +## 데이터 로드 준비 {#prepare-data-for-loading} + +[`data`](api/config/data-property.md) 속성은 객체 배열을 받으며, 각 객체는 하나의 데이터 행을 나타냅니다. 각 객체의 키는 Pivot 테이블에서 사용되는 차원과 값을 정의합니다. + +다음 코드 스니펫은 샘플 `data` 배열을 정의합니다: + +~~~jsx +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + { + name: "Argentina", + year: 2017, + continent: "South America", + form: "Republic", + gdp: 212.507, + oil: 1.732, + balance: 7.167, + when: new Date("1/15/2017") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 260.071, + oil: 2.845, + balance: 6.728, + when: new Date("6/16/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 324.405, + oil: 4.333, + balance: 5.99, + when: new Date("2/20/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 305.763, + oil: 2.626, + balance: 7.544, + when: new Date("8/17/2014") + }, + // 기타 데이터 +]; +~~~ + +:::info +필드 및 Pivot 구조 정의에 대한 자세한 내용은 [데이터 작업](guides/working-with-data.md)을 참조하십시오. +::: + +## 파일에서 데이터 로드 {#load-data-from-a-file} + +Pivot은 초기화 후 외부 파일에서 JSON 데이터를 로드합니다. 데이터, 필드, 구성이 포함된 소스 파일을 준비하십시오. + +다음 코드 스니펫은 별도 파일에서 `data`, `fields`, `getData()` 접근자를 정의합니다: + +~~~jsx +function getData() { + return { + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"], + } + } + }, + fields + }; +} +const fields = [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } +]; + +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + // 기타 데이터 +]; +~~~ + +페이지 마크업에 소스 데이터 파일 경로를 추가하십시오: + +~~~html title="index.html" + + + + +~~~ + +다음 코드 스니펫은 Pivot을 생성하고 준비된 파일에서 데이터를 로드합니다: + +~~~jsx +const { data, config, fields } = getData(); +const table = new pivot.Pivot("#root", { data, config, fields }); +~~~ + +## 서버에서 데이터 로드 {#load-data-from-a-server} + +서버 엔드포인트에서 데이터를 로드하려면 네이티브 `fetch` 메서드(또는 동등한 방법)로 요청을 보낸 후, 응답을 [`setConfig`](api/methods/setconfig-method.md)에 전달합니다. `setConfig`는 Pivot 구성을 업데이트하고 이전에 설정된 옵션을 유지합니다. + +다음 코드 스니펫은 빈 데이터로 Pivot을 초기화하고, 서버에서 데이터와 필드를 가져온 후 `setConfig`로 적용합니다: + +~~~jsx +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +Promise.all([ + fetch(server + "/data").then((res) => res.json()), + fetch(server + "/fields").then((res) => res.json()) +]).then(([data, fields]) => { + table.setConfig({ data, fields }); +}); +~~~ + +추가 정보는 다음 항목을 참조하십시오: [서버 작업](/guides/working-with-server) + +## CSV 데이터 로드 {#load-csv-data} + +Pivot은 외부 JS 파싱 라이브러리로 CSV 데이터를 JSON으로 변환한 후 사용할 수 있습니다. 변환된 데이터는 네이티브 JSON과 동일하게 동작합니다. + +아래 예제는 외부 [PapaParse](https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js) 라이브러리를 사용하여 버튼 클릭 시 데이터를 로드하고 변환합니다. `convert()` 헬퍼는 다음 파라미터를 받습니다: + +- `data` — CSV 데이터 문자열 +- `headers` — CSV 필드 이름 배열 +- `meta` — 필드 이름을 데이터 타입에 매핑하는 객체 + +다음 코드 스니펫은 Pivot을 생성하고, `convert()` 헬퍼를 정의하며, 버튼 클릭 시 [`setConfig`](api/methods/setconfig-method.md)를 통해 파싱된 CSV 데이터를 적용합니다: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +function convert(data, headers, meta) { + const header = headers.join(",") + "\n"; + const processedData = header + data; + + return Papa.parse(processedData, { + header: true, + dynamicTyping: true, + transform: (v, f) => { + return meta && meta[f] === "date" ? new Date(v) : v; + } + }); +} + +function fromCSV() { + const fields = [ + { id: "name", label: "Name", type: "text" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "gdp", label: "GDP", type: "number" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" }, + { id: "year", label: "Year", type: "number" }, + { id: "when", label: "When", type: "date" } + ]; + + const config = { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }; + + const headers = [ + "name", + "year", + "continent", + "form", + "gdp", + "oil", + "balance", + "when" + ]; + + // 날짜 필드를 명시적으로 표시하여 올바른 변환 적용 + const meta = { when: "date" }; + + const dataURL = "https://some-backend-url"; + fetch(dataURL) + .then(response => response.text()) + .then(text => convert(text, headers, meta)) + .then(data => { + table.setConfig({ + data: data.data, + fields, + config + }); + }); +} + +const importButton = document.createElement("button"); +importButton.addEventListener("click", fromCSV); +importButton.textContent = "Import"; + +document.body.appendChild(importButton); +~~~ + +## 예제 {#example} + +아래 스니펫은 JSON과 CSV 데이터를 로드합니다: + + + +**관련 샘플**: +- [Pivot 2. 날짜 형식](https://snippet.dhtmlx.com/shn1l794) +- [Pivot 2. 다양한 데이터셋](https://snippet.dhtmlx.com/6xtqge4i) +- [Pivot 2. 대용량 데이터셋](https://snippet.dhtmlx.com/e6qwqrys) + +**관련 문서**: [날짜 형식 지정](guides/localization.md#date-formatting) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/localization.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/localization.md new file mode 100644 index 0000000..359c1c9 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/localization.md @@ -0,0 +1,293 @@ +--- +sidebar_label: 로컬라이제이션 +title: 로컬라이제이션 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 로컬라이제이션에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# 로컬라이제이션 {#localization} + +Pivot를 사용하면 인터페이스의 모든 레이블을 로컬라이즈할 수 있습니다. 새 로케일을 생성하거나 기본 제공 로케일을 수정한 후, [`locale`](api/config/locale-property.md) 속성 또는 [`setLocale`](api/methods/setlocale-method.md) 메서드를 통해 Pivot에 로케일을 적용합니다. + +## 기본 로케일 {#default-locale} + +Pivot는 기본적으로 영어 로케일을 적용합니다. 다음 코드 스니펫은 내장 `en` 로케일의 구조를 보여줍니다: + +~~~jsx +const en = { + // pivot + pivot: { + sum: "Sum", + min: "Min", + max: "Max", + count: "Count", + counta: "CountA", + countunique: "CountUnique", + average: "Average", + median: "Median", + product: "Product", + stdev: "StDev", + stdevp: "StDevP", + var: "Var", + varp: "VarP", + "Raw date": "Raw date", + "Raw number": "Raw number", + "Raw text": "Raw text", + Year: "Year", + Month: "Month", + Day: "Day", + Hour: "Hour", + Minute: "Minute", + Total: "Total", + Values: "Values", + Rows: "Rows", + Columns: "Columns", + "Click on the plus icon(s) to add data": + "Click on the plus icon(s) to add data", + 'Click on "Show settings" to see the available configuration options': + 'Click on "Show settings" to see the available configuration options', + "Show settings": "Show settings", + "Hide settings": "Hide settings" + }, + + // query + query: { + "Add filter": "Add filter", + "Add Filter": "Add Filter", + "Add Group": "Add Group", + Edit: "Edit", + Delete: "Delete", + + "Select all": "Select all", + "Unselect all": "Unselect all", + + Cancel: "Cancel", + Apply: "Apply", + + and: "and", + or: "or", + in: "in", + + equal: "equal", + "not equal": "not equal", + contains: "contains", + "not contains": "not contains", + "begins with": "begins with", + "not begins with": "not begins with", + "ends with": "ends with", + "not ends with": "not ends with", + + greater: "greater", + "greater or equal": "greater or equal", + less: "less", + "less or equal": "less or equal", + between: "between", + "not between": "not between" + }, + + // calendar + calendar: { + monthFull: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ], + monthShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ], + + dayFull: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ], + + dayShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + hours: "Hours", + minutes: "Minutes", + done: "Done", + clear: "Clear", + today: "Today", + am: ["am", "AM"], + pm: ["pm", "PM"], + + weekStart: 7, + clockFormat: 24, + }, + + // core + core: { + ok: "OK", + cancel: "Cancel", + select: "Select", + "No data": "No data" + }, + + // formats + formats: { + dateFormat: "%d.%m.%Y", + timeFormat: "%H:%i" + }, + + lang: "en-US", +}; +~~~ + +## 로케일 적용 {#apply-a-locale} + +Pivot는 `pivot.locales` 객체를 통해 `en`, `de`, `cn` 세 가지 내장 로케일을 제공합니다. 초기화 시 [`locale`](api/config/locale-property.md) 속성에 내장 로케일을 전달하십시오. + +다음 코드 스니펫은 독일어 로케일로 Pivot를 초기화합니다: + +~~~jsx +new pivot.Pivot("#root", { + // other properties + locale: pivot.locales.de, +}); +~~~ + +커스텀 로케일을 적용하려면: + +- 로케일 객체를 생성하거나(또는 내장 로케일을 수정하여) 모든 텍스트 레이블에 대한 번역을 제공합니다(어떤 언어든 가능) +- [`locale`](api/config/locale-property.md) 속성 또는 [`setLocale`](api/methods/setlocale-method.md) 메서드를 통해 Pivot에 로케일을 적용합니다 + +다음 코드 스니펫은 Pivot를 생성한 후 `setLocale`을 사용하여 런타임에 커스텀 한국어 로케일을 적용합니다: + +~~~jsx +// Pivot 생성 +const widget = new pivot.Pivot("#root", { + data, + // other configuration properties +}); + +const ko = { /* object with locale */ }; +widget.setLocale(ko); +~~~ + +:::tip +인수 없이(또는 `null`을 인수로) [`setLocale`](api/methods/setlocale-method.md)을 호출하면 Pivot가 기본 영어 로케일로 초기화됩니다. +::: + +## 날짜 형식 지정 {#date-formatting} + +Pivot는 날짜를 `Date` 객체로 받습니다. 데이터를 Pivot에 전달하기 전에 문자열 값을 `Date`로 파싱하십시오. 기본 `dateFormat`은 현재 로케일에서 가져온 `"%d.%m.%Y"`입니다. + +모든 날짜 필드의 형식을 변경하려면 [`locale`](api/config/locale-property.md) 속성의 `formats` 객체에서 `dateFormat`에 새 값을 설정하십시오. + +다음 코드 스니펫은 문자열 날짜를 `Date` 객체로 파싱한 후, 커스텀 `dateFormat`으로 Pivot를 초기화하고 `setConfig`를 통해 런타임에 형식을 업데이트합니다: + +~~~jsx {17} +function setFormat(value) { + table.setConfig({ locale: { formats: { dateFormat: value } } }); +} + +// 날짜 문자열을 Date 객체로 변환 +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + locale: { formats: { dateFormat: "%d %M %Y %H:%i" } }, + fields, + data: dataset, + config: { + rows: ["state"], + columns: ["product_line", "product_type"], + values: [ + { + field: "date", + method: "min" + }, + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + } + ] + } +}); +~~~ + +특정 필드에 커스텀 형식을 설정하려면 [`fields`](api/config/fields-property.md) 속성의 `format` 파라미터를 사용하십시오. [필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields)을 참조하십시오. + +## 날짜 및 시간 형식 문자 {#date-and-time-format-characters} + +Pivot는 날짜 및 시간 형식을 정의하기 위해 다음 문자들을 사용합니다: + +| 문자 | 정의 | 예시 | +| :-------- | :------------------------------------------------ |:------------------------| +| %d | 앞에 0이 붙는 숫자로 표시된 일 | 01부터 31까지 | +| %j | 숫자로 표시된 일 | 1부터 31까지 | +| %D | 요일의 약어(단축 이름) | Su Mo Tu Sat | +| %l | 요일의 전체 이름 | Sunday Monday Tuesday | +| %W | 앞에 0이 붙는 숫자로 표시된 주(월요일을 첫째 날로 사용) | 01부터 52/53까지 | +| %m | 앞에 0이 붙는 숫자로 표시된 월 | 01부터 12까지 | +| %n | 숫자로 표시된 월 | 1부터 12까지 | +| %M | 월의 약어(단축 이름) | Jan Feb Mar | +| %F | 월의 전체 이름 | January February March | +| %y | 2자리 숫자로 표시된 연도 | 24 | +| %Y | 4자리 숫자로 표시된 연도 | 2024 | +| %h | 앞에 0이 붙는 12시간 형식의 시 | 01부터 12까지 | +| %g | 12시간 형식의 시 | 1부터 12까지 | +| %H | 앞에 0이 붙는 24시간 형식의 시 | 00부터 23까지 | +| %G | 24시간 형식의 시 | 0부터 23까지 | +| %i | 앞에 0이 붙는 분 | 01부터 59까지 | +| %s | 앞에 0이 붙는 초 | 01부터 59까지 | +| %S | 밀리초 | 128 | +| %a | am 또는 pm | am(자정부터 정오까지) 및 pm(정오부터 자정까지)| +| %A | AM 또는 PM | AM(자정부터 정오까지) 및 PM(정오부터 자정까지)| +| %c | ISO 8601 날짜 형식으로 날짜와 시간 표시 | 2024-10-04T05:04:09 | + +2024년 9월 20일 16:47:08.128을 *2024-09-20 16:47:08.128*로 표시하려면 `"%Y-%m-%d %H:%i:%s.%S"` 형식을 사용하십시오. + +## 숫자 형식 지정 {#number-formatting} + +Pivot는 현재 로케일의 `lang` 값을 기반으로 모든 `number` 필드를 로컬라이즈합니다. 위젯은 [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) 사양을 사용합니다. 기본 설정은 소수 자릿수를 3자리로 제한하고 정수 부분에 그룹 구분자를 적용합니다. + +특정 숫자 필드의 형식 지정을 건너뛰거나 커스텀 형식을 설정하려면 [`fields`](api/config/fields-property.md) 속성의 `format` 파라미터를 사용하십시오. `format`을 `false`로 설정하면 형식 지정이 비활성화되고, 형식 설정이 담긴 객체로 설정할 수도 있습니다([필드에 형식 적용](guides/working-with-data.md#applying-formats-to-fields) 참조). + +다음 코드 스니펫은 `year` 필드의 숫자 형식 지정을 비활성화합니다: + +~~~jsx +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +## 예제 {#example} + +아래 스니펫은 여러 로케일 간 전환을 보여줍니다: + + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/stylization.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/stylization.md new file mode 100644 index 0000000..53786da --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/stylization.md @@ -0,0 +1,266 @@ +--- +sidebar_label: 스타일링 +title: 스타일링 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 스타일링에 대해 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# 스타일링 {#styling} + +Pivot은 기본 테마를 제공하며, 사용자 정의를 위한 CSS 변수와 유틸리티 클래스를 노출합니다. 위젯 컨테이너(또는 상위 요소)에서 변수를 재정의하여 색상, 테두리 및 기타 시각적 속성을 변경할 수 있습니다. + +## 기본 스타일 {#default-style} + +Pivot의 기본 테마는 **Material**입니다. 다음 CSS 코드는 Material 테마가 위젯 컨테이너에 설정하는 변수를 보여줍니다: + +~~~css +.wx-material-theme { + --wx-theme-name: material; + --wx-pivot-primary-hover: #194e9e; + --wx-pivot-border-color: var(--wx-color-font-disabled); + --wx-pivot-field-hover: linear-gradient( + rgba(0, 0, 0, 0.1) 0%, + rgba(0, 0, 0, 0.1) 100% + ); +} +~~~ + +:::tip 참고 +Pivot의 향후 버전에서는 CSS 변수 이름이 변경될 수 있습니다. 업그레이드 후 변수 이름을 확인하고, 표시 문제가 발생하지 않도록 코드에서 업데이트하십시오. +::: + +## 내장 테마 {#built-in-theme} + +Pivot은 하나의 내장 테마인 **Material**을 제공합니다. 위젯 컨테이너에 테마 클래스를 추가하거나, 페이지에 미리 빌드된 스킨 스타일시트를 포함하여 테마를 적용할 수 있습니다. + +다음 코드는 위젯 컨테이너에 `wx-material-theme` 클래스를 추가하여 Material 테마를 적용합니다: + +~~~html {} + +
+~~~ + +다음 코드는 Material 스킨 스타일시트를 직접 포함합니다: + +~~~html {} + +~~~ + +## 내장 테마 사용자 정의 {#customize-built-in-theme} + +`.wx-material-theme` 선택자에서 Material 테마 변수를 재정의하여 색상, 테두리 및 기타 시각적 속성을 변경할 수 있습니다. + +아래 예제는 Material 테마 변수를 재정의하여 Pivot을 어두운 색상 구성표로 렌더링합니다: + +~~~html + + +~~~ + +## 사용자 정의 스타일 {#custom-style} + +위젯 컨테이너에 적용된 사용자 정의 클래스에서 CSS 변수를 재정의하여 Pivot의 외관을 변경할 수 있습니다. + +아래 예제는 `.demo` 클래스를 통해 Pivot에 사용자 정의 스타일을 적용합니다: + +~~~html +
+ +~~~ + +## 스크롤 스타일 {#scroll-style} + +`.wx-styled-scroll` CSS 클래스를 사용하여 Pivot 스크롤 바에 사용자 정의 스타일을 적용하십시오. 사용 전에 브라우저 호환성을 확인하십시오: [caniuse: CSS Scrollbar](https://caniuse.com/css-scrollbar). + +다음 코드는 위젯 컨테이너에 스타일이 적용된 스크롤 바를 활성화합니다: + +~~~html {} title="index.html" + +
+~~~ + +## 셀 스타일 {#cell-style} + +본문 또는 푸터 셀에 스타일을 적용하려면 [`tableShape`](api/config/tableshape-property.md) 속성의 `cellStyle` 파라미터를 사용하십시오. 헤더 셀에 스타일을 적용하려면 [`headerShape`](api/config/headershape-property.md) 속성의 `cellStyle` 파라미터를 사용하십시오. 두 경우 모두 `cellStyle` 함수는 Pivot이 셀에 적용할 CSS 클래스 이름을 반환합니다. + +아래 예제는 본문 셀과 헤더 셀에 스타일을 적용합니다: + +- 본문 셀은 셀 값(예: `status` 필드의 `"Down"`, `"Up"`, `"Idle"`)과 합계 값(40보다 크거나 5보다 작은 경우)에 따라 클래스를 받습니다. +- 헤더 셀은 `streaming` 필드의 값에 따라 클래스를 받습니다 — `"no"`이면 `status-down`, 다른 값이면 `status-up` + +~~~jsx +const widget = new pivot.Pivot("#pivot", { + tableShape: { + totalColumn: true, + totalRow:true, + cellStyle: (field, value, area, method, isTotal) => { + if (field === "status" && area === "rows" && value) { + if (value === "Down") { + return "status-down"; + } else if (value === "Up") { + return "status-up"; + } else if (value === "Idle") { + return "status-idle"; + } + } + if(isTotal ==="column" && area == "values"){ + if(value > 40) + return "status-up"; + else if (value < 5) + return "status-down"; + } + } + }, + headerShape:{ + cellStyle:(field, value, area, method, isTotal) => { + if(field == "streaming") + return value ==="no"?"status-down":"status-up"; + } + }, + fields, + data: dataset, + config: { + rows: [ + "protocol", + "status", + ], + columns: [ + "streaming" + ], + values: [ + { + field: "id", + method: "count" + } + ] + } +}); +~~~ + +## 셀의 값 표시 {#mark-values-in-cells} + +[`tableShape`](api/config/tableshape-property.md) 속성의 `marks` 파라미터를 사용하여 조건을 충족하는 셀에 CSS 클래스를 적용하십시오. `marks`의 각 항목은 CSS 클래스 이름(키)과 규칙(값)을 쌍으로 연결합니다. + +규칙은 사전 정의된 문자열(`"max"` 또는 `"min"`)이거나 사용자 정의 함수 `(value, columnData, rowData) => boolean`입니다. 함수가 `true`를 반환하면 Pivot은 해당 셀에 CSS 클래스를 추가합니다. + +`marks`를 적용하기 전에 스타일시트에 CSS 클래스를 미리 생성하십시오. + +아래 예제는 최솟값과 최댓값이 있는 셀을 강조 표시하고, 사용자 정의 함수를 사용하여 2보다 큰 비정수 값을 표시합니다: + +~~~jsx {18-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + marks: { + // 내장 marks (최솟값/최댓값 강조 표시) + min_cell: "min", + max_cell: "max", + // 사용자 정의 mark + g_avg: v => (v % 1 !== 0) && v > 2 + } + } +}); +~~~ + +다음 코드는 위의 `marks` 객체에서 참조하는 CSS 클래스를 정의합니다: + +~~~html title="index.html" + +~~~ + +## 특정 CSS 클래스 {#specific-css-classes} + +Pivot은 테이블 요소를 세밀하게 제어할 수 있는 여러 유틸리티 CSS 클래스를 제공하며, 이를 재정의할 수 있습니다. + +Pivot은 내장 `.wx-number` CSS 클래스를 통해 본문 셀의 숫자를 오른쪽으로 정렬합니다. 단, [`tableShape`](api/config/tableshape-property.md)에서 `tree: true`가 설정된 경우(트리 모드)의 계층적 열은 예외입니다. 기본 숫자 정렬을 초기화하려면 해당 클래스를 재정의하십시오. + +다음 코드는 본문 셀의 숫자를 왼쪽으로 정렬합니다: + +~~~html + +~~~ + +합계 열에 스타일을 적용하려면 `.wx-total` CSS 클래스를 재정의하십시오. + +다음 코드는 합계 셀에 밝은 배경과 굵은 글꼴 두께를 적용합니다: + +~~~html + +~~~ + +## 예제 {#example} + +아래 코드는 Pivot에 사용자 정의 스타일을 적용합니다: + + + +**관련 샘플**: + +- [Pivot 2. 합계 열에 대한 스타일링 (사용자 정의 CSS)](https://snippet.dhtmlx.com/9lkdbzmm) +- [Pivot 2. 셀에 대한 최솟값/최댓값 및 사용자 정의 marks (조건부 형식)](https://snippet.dhtmlx.com/4cm4asbd) +- [Pivot 2. 교대 행 색상 (줄무늬 행, 얼룩말 줄무늬)](https://snippet.dhtmlx.com/0cm0uko2) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/typescript-support.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/typescript-support.md new file mode 100644 index 0000000..4af2dd4 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/typescript-support.md @@ -0,0 +1,17 @@ +--- +sidebar_label: TypeScript 지원 +title: TypeScript 지원 +description: DHTMLX JavaScript Pivot 라이브러리와 함께 TypeScript를 사용하는 방법을 문서에서 확인하실 수 있습니다. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# TypeScript 지원 {#typescript-support} + +DHTMLX Pivot은 v2.0부터 TypeScript 정의를 제공합니다. 별도의 추가 설정 없이 바로 사용할 수 있습니다. + +:::info +[Snippet Tool](https://snippet.dhtmlx.com/y2buoahe)에서 Pivot을 직접 체험해 보세요. +::: + +## TypeScript의 장점 {#advantages-of-typescript} + +타입 검사와 자동 완성 기능을 통해 오류를 조기에 발견할 수 있으며, 번들로 제공되는 정의 파일을 통해 DHTMLX Pivot API가 요구하는 데이터 타입을 정확히 확인할 수 있습니다. diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/working-with-data.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/working-with-data.md new file mode 100644 index 0000000..0afdb45 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/working-with-data.md @@ -0,0 +1,687 @@ +--- +sidebar_label: 데이터 작업 +title: 데이터 작업 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 데이터 작업 방법을 살펴볼 수 있습니다. 개발자 가이드와 API 참조를 확인하고, 코드 예제와 라이브 데모를 직접 실행해 보세요. 또한 DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# 데이터 작업 + +이 페이지에서는 Pivot에서 데이터를 집계, 포맷, 정렬, 필터링 및 전처리하는 방법을 설명합니다. 데이터 로드 및 내보내기에 관한 안내는 [데이터 로드](guides/loading-data.md)와 [데이터 내보내기](guides/exporting-data.md)를 참조하십시오. + +## 필드 정의 {#define-fields} + +[`fields`](api/config/fields-property.md) 속성을 사용하여 Pivot이 행, 열, 값에 배치할 수 있는 필드를 선언합니다. `fields` 배열의 각 항목은 하나의 필드를 설명하며, 해당 필드의 ID, 레이블, 데이터 타입을 포함합니다. + +다음 코드 예제는 다섯 개의 필드로 Pivot을 초기화합니다: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields: [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } + ], + data, + config: {...} +}); +~~~ + +## 필드에 포맷 적용 {#applying-formats-to-fields} + +Pivot은 현재 로케일을 기준으로 숫자 및 날짜 필드에 기본 포맷을 적용합니다. 자세한 내용은 [날짜 포맷](guides/localization.md#date-formatting) 및 [숫자 포맷](guides/localization.md#number-formatting)을 참조하십시오. + +특정 필드의 기본값을 재정의하려면 [`fields`](api/config/fields-property.md) 속성의 `format` 파라미터를 설정합니다. + +### 숫자 필드 포맷 {#format-numeric-fields} + +`prefix`와 `suffix`를 사용하여 숫자 값 앞뒤에 텍스트를 추가하고, `maximumFractionDigits`로 소수점 자릿수를 제어합니다. 예를 들어 `12.345`를 `"12.35 EUR"`로 표시하려면 suffix를 `" EUR"`로, `maximumFractionDigits`를 `2`로 설정합니다: + +~~~js +const fields = [ + { id: "sales", type: "number", format: { suffix: " EUR", maximumFractionDigits: 2 } }, +]; +~~~ + +기본 포맷은 숫자 필드의 소수점 자릿수를 3자리로 제한하고 정수 부분에 천 단위 구분자를 적용합니다. 포맷을 완전히 비활성화하려면 `format`을 `false`로 설정합니다: + +~~~js +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +아래 예제는 `marketing`, `profit`, `sales`를 `$` 접두사와 고정 2자리 소수점이 있는 통화 필드로 지정합니다: + +~~~jsx +// 사전 정의된 데이터셋과 필드로 Pivot 초기화 +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { field: "marketing", method: "sum" }, + // 다른 값들 + + ], + }, + fields:[ + // 커스텀 포맷 + { id: "marketing", label: "Marketing", type:"number", format:{ + prefix: "$", minimumFractionDigits: 2, maximumFractionDigits: 2 } + } + ] +}); +~~~ + +### 날짜 필드 포맷 {#format-date-fields} + +단일 필드에 대해 로케일 전체의 `dateFormat`을 재정의하려면 [`fields`](api/config/fields-property.md)의 `format` 파라미터를 날짜 포맷 문자열로 설정합니다. + +다음 코드 예제는 `date` 필드의 포맷을 `"%M %d, %Y"`로 설정합니다: + +~~~jsx +const fields = [ + { id: "date", type: "date", format: "%M %d, %Y" }, +]; +~~~ + +아래 예제는 문자열 날짜를 `Date` 객체로 변환한 다음, `date` 필드에 대해 `"%d %M %Y %H:%i"` 포맷으로 Pivot을 초기화합니다. 필드 값은 `"24 April 2025 14:30"`과 같은 레이블로 표시됩니다. + +~~~jsx +// 날짜 문자열을 Date 객체로 변환 +const dateFields = fields.filter(f => f.type === "date"); +dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v === "string") { + item[f.id] = new Date(v); + } + }); +}); + +// 필드별 날짜 포맷으로 Pivot 초기화 +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state"], + columns: ["product_type"], + values: [ + { field: "date", method: "min" }, + { field: "profit", method: "sum" }, + { field: "sales", method: "sum" } + ] + }, + fields:[ + // 커스텀 포맷: 일 월 년 시:분 + { id: "date", label: "Date", type: "date", format: "%d %M %Y %H:%i" } + ] +}); +~~~ + +:::note +`xlsx` 내보내기 포맷의 경우, Pivot은 날짜 및 숫자 필드를 기본 포맷(또는 [`fields`](api/config/fields-property.md) 속성으로 정의된 포맷)과 함께 원시 값으로 내보냅니다. 필드에 템플릿이 정의된 경우([`tableShape`](api/config/tableshape-property.md) 속성 참조), Pivot은 해당 템플릿이 생성한 렌더링된 값을 내보냅니다. `template`과 `format`이 모두 설정된 경우, 템플릿이 포맷보다 우선합니다. +::: + +## Pivot 구조 정의 {#define-pivot-structure} + +[`config`](api/config/config-property.md) 속성을 사용하여 행, 열, 집계 값으로 표시할 필드와 데이터 필터링 방식을 선언합니다. `config` 속성에는 사전 정의된 값이 없으므로 데이터를 렌더링하려면 반드시 설정해야 합니다. 전체 파라미터 목록은 [`config`](api/config/config-property.md) 참조를 확인하십시오. + +다음 코드 예제는 `continent`와 `name`을 행에, `year`를 열에, 세 개의 집계를 값에, `name`에 대한 필터를 배치합니다: + +~~~jsx {4-18} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }, + fields, + filters: { + name: { + contains: "B" + } + } +}); +~~~ + +## 데이터 정렬 {#sorting-data} + +Pivot은 집계 중에 세 영역(값, 열, 행) 모두에서 정렬을 지원합니다. UI에서 사용자는 열 헤더를 클릭하여 정렬합니다. + +기본 정렬을 설정하려면 [`fields`](api/config/fields-property.md) 속성의 `sort` 파라미터를 사용합니다. 이 파라미터는 `"asc"`, `"desc"`, 또는 커스텀 비교 함수를 받습니다. + +아래 예제는 Pivot 위에 클릭 가능한 필드 레이블을 렌더링하고 클릭 시 정렬 방향을 전환합니다: + +~~~jsx +const bar = document.getElementById("bar"); + +let sorted = ["studio", "genre"]; +setFields(); +bar.addEventListener('click', (e) => switchSort(e.target.id), false); + +function setFields(){ + let html = ""; + let sortedFields = fields.filter(f => (sorted.indexOf(f.id) != -1)); + + sortedFields.forEach((f) =>{ + const order = f.sort || "asc"; + html += `
+ ${f.label} +
`; + }); + bar.innerHTML = html; +} + +function switchSort(id){ + fields.forEach(f => { + if(f.id == id){ + f.sort = f.sort != "desc" ? "desc" : "asc"; + } + }); + // Pivot fields 업데이트 + table.setConfig({ fields }); + // 아이콘 새로고침 + setFields(bar, fields); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +UI에서의 정렬은 기본적으로 활성화되어 있습니다. 비활성화하려면 [`columnShape`](api/config/columnshape-property.md) 속성의 `sort` 파라미터를 `false`로 설정합니다. + +다음 코드 예제는 UI 정렬을 비활성화합니다: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +## 데이터 필터링 {#filtering-data} + +Pivot은 필드 데이터 타입에 연결된 필터를 지원합니다. 초기화 후 Pivot UI를 통해 필터를 설정하거나, [`config`](api/config/config-property.md) 속성의 `filters` 객체를 통해 선언적으로 설정할 수 있습니다. + +UI에서 필터는 각 필드의 드롭다운 목록으로 표시됩니다. + +#### 필터 타입 {#filter-types} + +Pivot은 데이터 타입별로 다음과 같은 필터 조건을 지원합니다: + +- 텍스트 필드 — `equal`, `notEqual`, `contains`, `notContains`, `beginsWith`, `notBeginsWith`, `endsWith`, `notEndsWith`, `includes` +- 숫자 필드 — `equal`, `notEqual`, `greater`, `greaterOrEqual`, `less`, `lessOrEqual`, `contains`, `notContains`, `beginsWith`, `notBeginsWith`, `endsWith`, `notEndsWith` +- 날짜 필드 — `equal`, `notEqual`, `greater`, `greaterOrEqual`, `less`, `lessOrEqual`, `between`, `notBetween`, `includes` + +`includes` 규칙은 필터를 특정 허용 값 집합으로 제한합니다. + +#### 필터 추가 {#add-a-filter} + +필터를 선언하려면 [`config`](api/config/config-property.md) 속성에 `filters` 객체를 추가하고 필드 ID를 키로 사용합니다. 각 값은 필터 조건 객체입니다. + +다음 코드 예제는 두 개의 필터를 적용합니다 — `genre`에 하나(`"D"`를 포함하는 값, `"Drama"`로 제한)와 `title`에 하나(`"A"`를 포함하는 값): + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // 다른 필드("title")에 대한 필터 + contains: "A" + } + } + } +}); +~~~ + +:::info +Table widget API를 통해 데이터를 필터링하려면, [`getTable`](api/methods/gettable-method.md) 메서드로 Table 인스턴스에 접근하고 [`filter-rows`](api/table/filter-rows.md) 이벤트를 사용합니다. +::: + +## 로드되는 데이터 제한 {#limiting-loaded-data} + +매우 큰 데이터셋에서 컴포넌트가 멈추는 것을 방지하기 위해, [`limits`](api/config/limits-property.md) 속성으로 최종 데이터셋의 행과 열 수를 제한합니다. Pivot은 제한에 도달하면 렌더링을 중단합니다. 기본 제한은 행 10000개, 열 5000개입니다. + +:::note +제한은 대규모 데이터셋에 적용됩니다. 이 숫자는 근사값이며, Pivot은 정확한 행/열 수를 보장하지 않습니다. +::: + +다음 코드 예제는 데이터셋을 행 10개, 열 3개로 제한합니다: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + limits: { rows: 10, columns: 3 } +}); +~~~ + +## 수학 메서드 적용 {#applying-maths-methods} + +### 기본 메서드 {#default-methods} + +Pivot에는 다음과 같은 기본 집계 메서드가 포함되어 있습니다: + +- `sum` (숫자 값만) — 선택된 모든 값을 합산하며, 빈 셀, `TRUE`와 같은 논리 값, 텍스트는 무시합니다 +- `min` (숫자 및 날짜 값) — 최솟값을 반환하며, 빈 셀, 논리 값, 텍스트는 무시합니다. 입력에 숫자가 없으면 `0`을 반환합니다 +- `max` (숫자 및 날짜 값) — 최댓값을 반환하며, 빈 셀, 논리 값, 텍스트는 무시합니다. 입력에 숫자가 없으면 `0`을 반환합니다 +- `count` (숫자, 텍스트, 날짜 값) — 비어 있지 않은 셀을 계산하며, 새로 추가된 모든 필드에 기본으로 할당되는 메서드입니다 +- `countunique` (숫자 및 텍스트 값) — 입력에서 고유한 값의 수를 계산합니다 +- `average` (숫자 값만) — 입력의 산술 평균을 계산하며, 빈 셀, 논리 값, 텍스트는 무시합니다. 값이 0인 셀은 포함합니다 +- `counta` (숫자, 텍스트, 날짜 값) — 숫자, 날짜, 텍스트를 포함한 모든 비어 있지 않은 값을 계산합니다 +- `median` (숫자 값만) — 입력의 중앙값을 반환합니다 +- `product` (숫자 값만) — 입력의 모든 숫자의 곱을 반환합니다 +- `stdev` (숫자 값만) — 표준 편차이며, 입력을 더 큰 집합의 표본으로 처리합니다 +- `stdevp` (숫자 값만) — 표준 편차이며, 입력을 전체 모집단으로 처리합니다 +- `var` (숫자 값만) — 분산이며, 입력을 더 큰 집합의 표본으로 처리합니다 +- `varp` (숫자 값만) — 분산이며, 입력을 전체 모집단으로 처리합니다 + +다음 코드 예제는 내장 메서드 정의를 보여줍니다: + +~~~jsx +const defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +[`config`](api/config/config-property.md) 속성의 `values` 파라미터를 통해 기본 메서드를 적용합니다. [값 정의](#options-for-defining-values)를 참조하십시오. + +다음 코드 예제는 `title` 필드에 `count`를, `score` 필드에 `max`를 할당합니다: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + // 필드 id + field: "title", + // 메서드 + method: "count" + }, + { + id: "score", + method: "max" + } + ] + } +}); +~~~ + +### 값 정의 {#options-for-defining-values} + +`values`의 각 항목을 다음 두 가지 동등한 형식 중 하나로 정의합니다: + +- `"operation(fieldID)"` 형식의 문자열 +- `{ field: string, method: string }` 객체 (두 필드 모두 필수) + +다음 코드 예제는 같은 `values` 배열에서 두 형식을 모두 사용합니다: + +~~~jsx +values: [ + "sum(sales)", // 방법 1 + { field: "sales", method: "sum" } // 방법 2 +] +~~~ + +### 기본 메서드 재정의 {#override-the-default-method} + +새로 추가된 각 필드에 대해 Pivot은 해당 데이터 타입에 사용 가능한 첫 번째 메서드를 할당합니다. 이 동작을 변경하려면 [`api.intercept`](api/internal/intercept-method.md) 메서드로 `add-field` 이벤트를 인터셉트합니다. + +아래 예제는 `add-field`를 인터셉트하여 숫자 필드가 추가될 때마다 `max` 메서드를 강제로 적용합니다: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count", + }, + { + field: "score", + method: "max", + }, + ], + }, +}); +// 새로 추가된 숫자 필드에 대한 기본 메서드 재정의 +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "max"; + } +}); +~~~ + +### 커스텀 수학 메서드 추가 {#add-custom-math-methods} + +커스텀 집계 메서드를 추가하려면 [`methods`](api/config/methods-property.md) 속성을 사용합니다. 각 항목은 메서드 이름(키)과 `handler` 함수 및 메타데이터를 포함하는 구성 객체를 쌍으로 구성합니다. `handler`는 값 배열을 받아 단일 집계 값을 반환합니다. + +아래 예제는 두 개의 날짜별 메서드를 추가합니다. `countunique_date`는 숫자 타임스탬프를 기준으로 고유한 날짜를 계산합니다. `average_date`는 타임스탬프의 평균을 구해 평균 날짜를 반환합니다: + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique", + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// "count" 및 "unique count" 결과에 대해 정수 표시 +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// 날짜 문자열을 Date 객체로 변환 +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +## 프레디케이트로 데이터 처리 {#processing-data-with-predicates} + +프레디케이트(predicate)는 Pivot이 행이나 열에서 데이터를 사용하기 전에 원시 필드 데이터를 변환하는 전처리 함수입니다. 예를 들어, 프레디케이트는 집계 전에 날짜를 월별로 그룹화할 수 있습니다. + +다음 코드 예제는 Pivot이 기본적으로 적용하는 내장 날짜 프레디케이트를 보여줍니다: + +~~~jsx +const defaultPredicates = { + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +커스텀 프레디케이트를 추가하려면 [`predicates`](api/config/predicates-property.md) 속성을 구성합니다. 각 항목은 프레디케이트 ID(키)와 구성 객체를 쌍으로 구성합니다: + +- `type` — 이 프레디케이트가 받는 필드 타입 (`"number"`, `"date"`, `"text"` 또는 배열) +- `label` — 행/열의 GUI 드롭다운에 표시되는 프레디케이트 레이블 +- `handler` — 값을 변환하고 처리된 값을 반환하는 함수 +- `template` — 처리된 값의 표시 방식을 제어하는 선택적 함수 +- `field` — 프레디케이트를 특정 필드로 제한하는 선택적 함수 +- `filter` — 필터 타입이 `type`과 달라야 하거나, 데이터 포맷이 `template`과 달라야 할 때 사용하는 선택적 필터 구성 + +커스텀 프레디케이트를 사용하려면 해당 ID를 프레디케이트가 적용될 행 또는 열의 `method`로 설정합니다. + +다음 코드 예제는 두 개의 커스텀 프레디케이트(`monthYear`와 `profitSign`)를 등록하고 `columns` 구성에 적용합니다: + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// 날짜 문자열을 Date 객체로 변환 +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +## 합계 값이 있는 열과 행 추가 {#add-columns-and-rows-with-total-values} + +[`tableShape`](api/config/tableshape-property.md) 속성을 사용하여 오른쪽에 합계 열(`totalColumn: true`)이나 합계 푸터 행(`totalRow: true`)을 렌더링합니다. + +다음 코드 예제는 합계 열과 합계 행을 모두 활성화합니다: + +~~~jsx {2-5} +const table = new pivot.Pivot("#root", { + tableShape: { + totalRow: true, + totalColumn: true + }, + fields, + data, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + } + ] + } +}); +~~~ + +## 예제 {#example} + +아래 코드 예제는 커스텀 수학 연산을 적용합니다: + + + +**관련 샘플**: + +- [Pivot 2. 별칭이 있는 데이터셋](https://snippet.dhtmlx.com/7vc68rqd) +- [Pivot 2. 필드 포맷 정의](https://snippet.dhtmlx.com/77nc4j8v) +- [Pivot 2. 외부 필터](https://snippet.dhtmlx.com/s7tc9g4z) +- [Pivot 2. 열과 행의 총합계](https://snippet.dhtmlx.com/f0ag0t9t) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/guides/working-with-server.md b/i18n/ko/docusaurus-plugin-content-docs/current/guides/working-with-server.md new file mode 100644 index 0000000..c65cbcd --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/guides/working-with-server.md @@ -0,0 +1,172 @@ +--- +sidebar_label: 서버와 연동하기 +title: 서버와 연동하기 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 Pivot을 백엔드와 통합하는 방법을 살펴볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 참고하고, 코드 예제와 라이브 데모를 직접 체험해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +Pivot은 전적으로 브라우저에서 실행됩니다. 위젯은 원시 행 배열과 [`config`](/api/config/config-property)(rows / columns / values)를 받아 클라이언트 측에서 행을 집계합니다. 내장된 전송 계층은 없지만, 공개 API에는 백엔드와의 왕복 통신을 위한 훅이 노출되어 있습니다. + +일반적인 통합은 세 부분으로 구성됩니다. + +1. **데이터 로드** — 초기화 시 서버에서 집계되지 않은 원시 데이터를 불러옵니다 +2. **config 저장** — 사용자가 레이아웃을 변경할 때 저장하여 세션을 나중에 재개할 수 있도록 합니다 +3. **집계된 테이블 저장** — 서버에서 집계 결과의 스냅샷이 필요할 때 저장합니다 + +## 서버에서 원시 데이터 로드하기 {#load-raw-data-from-the-server} + +[`data`](/api/config/data-property) 프로퍼티는 원시 행 객체의 배열을 받습니다. Pivot이 행을 직접 집계하므로 서버는 집계되지 않은 데이터를 반환합니다. + +`fetch`(또는 다른 HTTP 클라이언트)를 사용하여 데이터와 필드를 가져온 뒤, 응답이 도착하면 위젯을 생성합니다. + +~~~html +
+ + +~~~ + +서버가 날짜 필드를 ISO 문자열로 반환하는 경우, 배열을 Pivot에 전달하기 전에 `Date` 인스턴스로 변환하세요. 날짜 타입 필드의 집계 메서드는 실제 `Date` 값을 필요로 합니다. + +~~~jsx +data.forEach(row => { + if (typeof row.when === "string") row.when = new Date(row.when); +}); +~~~ + +:::info +**참고 항목**: +- [데이터 로드하기](/guides/loading-data) +- [날짜 포맷](/guides/localization#date-formatting) +::: + +## 세션 재개를 위한 사용자 레이아웃 저장하기 {#save-the-users-layout-to-resume-the-session} + +사용자가 이전에 사용하던 레이아웃으로 돌아올 수 있도록 하려면, 변경이 있을 때마다 [`config`](/api/config/config-property) 객체를 저장하세요. [`update-config`](/api/events/update-config-event) 이벤트는 사용자가 UI를 통해 레이아웃을 편집할 때 발생합니다. 페이로드는 `{ rows, columns, values, filters }` 형태의 처리된 config입니다. + +이벤트를 수정 없이 관찰하려면 [`api.on()`](/api/internal/on-method)을 사용하세요. 핸들러에서 이벤트 페이로드를 변경해야 할 경우에는 [`api.intercept()`](/api/internal/intercept-method)로 전환하세요. + +아래 예제는 `update-config` 이벤트를 구독하고 새 레이아웃을 서버에 POST합니다. + +~~~html +
+ + +~~~ + +다음 방문 시, `/config`에서 저장된 config를 반환하고 초기화 시 `config` 프로퍼티로 전달하세요. 위젯이 이전 레이아웃으로 시작됩니다. 위젯이 이미 존재한 후 레이아웃이 도착한다면, [`setConfig()`](/api/methods/setconfig-method) 메서드로 저장된 config를 적용하세요. + +사용자가 구성 패널에서 필드를 드래그할 때 빈번한 업데이트로 서버에 부하가 걸릴 수 있습니다. 타이머로 POST 요청을 디바운스하세요. + +~~~jsx +let saveTimer; +table.api.on("update-config", newConfig => { + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/config", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(newConfig), + }); + }, 300); +}); +~~~ + +:::note +`update-config` 페이로드는 *처리된* 구성입니다. Pivot은 필드 참조를 `{ field, method }` 형태로 정규화할 수 있습니다. 처리된 형태를 초기화 시 `config` 프로퍼티로 그대로 전달하세요. 별도의 변환은 필요하지 않습니다. +::: + +:::tip +핸들러에서 `false`를 반환하면 레이아웃 변경을 차단할 수 있습니다. 서버 측 유효성 검사를 통과한 경우에만 저장하도록 제어할 때 활용하세요. +::: + +## 집계된 테이블 저장하기 {#save-the-aggregated-table} + +때로는 *결과* 자체가 핵심 값이 됩니다. 렌더링된 테이블의 서버 측 캐시, 주기적인 보고서, 또는 내보내기 파이프라인이 그 예입니다. [`render-table`](/api/events/render-table-event) 이벤트는 Pivot이 집계를 완료한 후 발생하며, `columns`, `data` 행, `footer`, `split` 등 완전히 집계된 테이블 정보를 담고 있습니다. + +아래 예제는 `render-table`을 구독하고 스냅샷을 서버에 POST하며, 초기 렌더링은 건너뜁니다. + +~~~jsx +const table = new pivot.Pivot("#root", { data, fields, config }); + +let firstRender = true; +let saveTimer; + +table.api.on("render-table", ({ config: tableConfig }) => { + // 첫 번째 집계에 의해 트리거되는 초기 렌더링을 건너뜁니다 + if (firstRender) { + firstRender = false; + return; + } + + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/snapshot", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + columns: tableConfig.columns, + data: tableConfig.data, + footer: tableConfig.footer, + split: tableConfig.split, + }), + }); + }, 300); +}); +~~~ + +:::note +`render-table` 이벤트는 `update-config`보다 더 자주 발생합니다. 정렬이나 확장/축소를 포함한 모든 재계산 시 이벤트가 실행됩니다. 핸들러를 디바운스하고 첫 번째 렌더링을 건너뛰어 실제 변경 사항당 POST가 한 번만 전송되도록 하세요. +::: + +:::tip +핸들러에서 `false`를 반환하면 렌더링을 방지할 수 있습니다. 서버에서 스냅샷을 거부하거나 읽기 전용 모드에서 활용하세요. +::: + +### 집계된 스냅샷 재사용하기 {#reload-an-aggregated-snapshot} + +Pivot은 집계된 테이블을 생성하며, 이미 집계된 데이터는 표시하지 않습니다. [`data`](/api/config/data-property) 프로퍼티는 항상 원시 행을 받습니다. 따라서 `render-table`에서 저장한 스냅샷은 다음과 같은 경우에 적합합니다. + +- 서버에서의 다운스트림 내보내기 파이프라인(CSV, XLSX) +- 저장된 `columns`와 `data`를 사용하는 일반 데이터 테이블로 렌더링하는 읽기 전용 뷰 +- 집계를 다시 실행하지 않고 다른 사용자에게 제공하는 캐시된 보고서 + +**관련 문서**: + +- [데이터 로드하기](/guides/loading-data) +- [데이터 내보내기](/guides/exporting-data) + +**관련 API**: + +- [`api.on()`](/api/internal/on-method) +- [`update-config`](/api/events/update-config-event) +- [`render-table`](/api/events/render-table-event) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/how-to-start.md b/i18n/ko/docusaurus-plugin-content-docs/current/how-to-start.md new file mode 100644 index 0000000..555901a --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/how-to-start.md @@ -0,0 +1,122 @@ +--- +sidebar_label: 시작하는 방법 +title: 시작하는 방법 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 DHTMLX Pivot 작업을 시작하는 방법을 알아보세요. 개발자 가이드와 API 레퍼런스를 탐색하고, 코드 예제와 라이브 데모를 체험하며, DHTMLX Pivot의 무료 30일 평가판을 다운로드하세요. +--- + +# 시작하는 방법 + +이 명확하고 포괄적인 튜토리얼은 페이지에 완전한 기능을 갖춘 Pivot를 구성하기 위해 필요한 단계를 안내합니다. + +![pivot-main](/assets/pivot_main.png) + +## 1단계. 패키지 다운로드 및 설치 {#step-1-downloading-and-installing-packages} + +[패키지를 다운로드](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml)하여 프로젝트 폴더에 압축을 푸세요. + +`yarn` 또는 `npm` 패키지 매니저를 사용하여 JavaScript Pivot을 프로젝트에 가져올 수 있습니다. + +:::info +Pivot을 React, Angular, Svelte 또는 Vue 프로젝트에 통합하려면 해당 [**통합 가이드**](/category/integration-with-frameworks/)를 참조하세요. +::: + +### npm 또는 yarn을 통한 체험판 Pivot 설치 {#installing-trial-pivot-via-npm-or-yarn} + +:::info +체험판 Pivot을 사용하려면 [**체험판 Pivot 패키지**](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml)를 다운로드하고 *README* 파일에 안내된 단계를 따르세요. 체험판 Pivot은 30일 동안만 사용 가능합니다. +::: + +### npm 또는 yarn을 통한 PRO Pivot 설치 {#installing-pro-pivot-via-npm-or-yarn} + +:::info +[고객 전용 영역](https://dhtmlx.com/clients/)에서 **npm** 로그인 및 비밀번호를 생성하여 DHTMLX 개인 **npm**에 직접 접근할 수 있습니다. 자세한 설치 가이드도 해당 페이지에서 확인할 수 있습니다. 개인 **npm** 접근은 독점 Pivot 라이선스가 활성 상태인 동안에만 가능합니다. +::: + +## 2단계. 소스 파일 포함 {#step-2-including-source-files} + +HTML 파일을 생성하고 *index.html*로 이름을 지정하는 것부터 시작하세요. 그런 다음 Pivot 소스 파일을 생성한 파일에 포함합니다. + +두 가지 필수 파일이 있습니다: + +- Pivot의 JS 파일 +- Pivot의 CSS 파일 + +~~~html {5-6} title="index.html" + + + + How to Start with Pivot + + + + + + + +~~~ + +## 3단계. Pivot 생성 {#step-3-creating-pivot} + +이제 페이지에 Pivot을 추가할 준비가 되었습니다. 먼저 Pivot을 위한 DIV 컨테이너를 생성합니다. + +~~~html {} title="index.html" + + + + How to Start with Pivot + + + + +
+ + + +~~~ + +## 4단계. Pivot 구성 {#step-4-configuring-pivot} + +다음으로 Pivot 컴포넌트가 초기화될 때 가질 구성 속성을 지정할 수 있습니다. + +Pivot 작업을 시작하려면 먼저 초기 데이터를 제공해야 합니다. 아래 예제는 다음과 같은 Pivot을 생성합니다: + +- *studio* 및 *genre*에 대한 행 +- *title* 열 +- *max* 방법을 사용한 *score*의 값 집계 + +**fields** 배열은 필드 ID, 표시 레이블, 데이터 타입을 정의하는 데 필요합니다. + +**data** 배열은 Pivot 위젯에 표시될 실제 데이터를 포함해야 합니다. 배열의 각 객체는 테이블의 행을 나타냅니다. + +**config** 객체는 Pivot 테이블의 구조를 정의합니다. 즉, 어떤 필드가 테이블의 행과 열로 적용되고 어떤 데이터 집계 방법이 필드에 적용되어야 하는지를 지정합니다. + +~~~jsx +const table = new pivot.Pivot("#root", { + //configuration properties + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## 다음 단계 {#whats-next} + +이것으로 완료입니다. 이 간단한 단계만으로 데이터 분석에 유용한 도구를 갖추게 되었습니다. 이제 작업을 시작하거나 JavaScript Pivot의 내부 세계를 계속 탐색할 수 있습니다: + +- [가이드](/category/guides) 페이지는 설치, 데이터 로딩, 스타일링 및 Pivot 구성을 원활하게 진행하는 데 도움이 되는 기타 유용한 팁에 대한 지침을 제공합니다 +- [API 레퍼런스](api/overview/main-overview.md)는 Pivot 기능에 대한 설명을 제공합니다 diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/index.md b/i18n/ko/docusaurus-plugin-content-docs/current/index.md new file mode 100644 index 0000000..3198541 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/index.md @@ -0,0 +1,103 @@ +--- +sidebar_label: Pivot 개요 +title: JavaScript Pivot 개요 +slug: / +description: DHTMLX JavaScript Pivot 라이브러리의 개요를 문서에서 확인할 수 있습니다. 개발자 가이드와 API 레퍼런스를 탐색하고, 코드 예제와 라이브 데모를 직접 사용해 보세요. DHTMLX Pivot 30일 무료 평가판도 다운로드할 수 있습니다. +--- + +# DHTMLX Pivot 개요 + +JavaScript Pivot 라이브러리는 대용량 데이터셋으로 피벗 테이블을 생성하기 위한 즉시 사용 가능한 컴포넌트입니다. 위젯 API는 웹 애플리케이션의 요구에 맞게 손쉽게 조정할 수 있습니다. 하나의 테이블 안에서 복잡한 데이터를 비교하고 분석하는 기능을 최종 사용자에게 제공합니다. + +## Pivot 구조 {#pivot-structure} + +Pivot UI는 구성 패널과 데이터 테이블, 두 가지 주요 컴포넌트로 구성됩니다. + +![Main](assets/pivot-main.png) + +## 구성 패널 {#configuration-panel} + +구성 패널에서는 테이블에 열과 행을 추가하고, 데이터 집계 방식을 정의하는 값 필드를 설정할 수 있습니다. 패널의 다음 영역을 통해 각 항목을 추가할 수 있습니다: + +- Values: 데이터 집계 방식(합계, 최솟값, 최댓값 등)을 정의하는 값을 추가할 수 있습니다 +- Columns: 테이블의 열을 구성합니다(어떤 필드를 열로 적용할지 정의) +- Rows: 테이블의 행으로 적용할 필드를 구성합니다 + +구성 패널을 숨기려면 **설정 숨기기** 버튼을 클릭하십시오: + +![config_panel](assets/config_panel.png) + +### Values 영역 {#values-area} + +**Values** 영역에서는 피벗 테이블 셀에 적용할 집계 방식(min, max, count 등)을 정의할 수 있습니다. 다음 작업을 수행할 수 있습니다: + +- Values 영역에 필드 추가 및 제거 +- 테이블 내 값의 순서와 우선순위 변경 +- 데이터 필터링 +- 테이블 필드에 적용할 연산 설정 + +자세한 내용은 [영역 내 연산](#operations-in-areas) 및 [필터](#filters) 섹션을 참조하십시오. + +### Columns 영역 {#columns-area} + +**Columns** 영역에서는 다음 작업을 수행할 수 있습니다: + +- 열 추가 및 제거(열로 적용된 필드 추가/제거) +- 테이블 내 열의 순서와 우선순위 변경 +- 데이터 필터링 + +자세한 내용은 [영역 내 연산](#operations-in-areas) 및 [필터](#filters) 섹션을 참조하십시오. + +### Rows 영역 {#rows-area} + +**Rows** 영역에 대한 구성 패널에서는 다음 작업을 수행할 수 있습니다: + +- 행 추가 및 제거(행으로 적용된 필드 추가/제거) +- 테이블 내 행의 순서와 우선순위 변경 +- 데이터 필터링 + +자세한 내용은 [영역 내 연산](#operations-in-areas) 및 [필터](#filters) 섹션을 참조하십시오. + +### 영역 내 연산 {#operations-in-areas} + +구성 패널의 세 영역 모두에서 테이블에 필드를 추가하거나 제거할 수 있습니다. 특정 필드를 행 또는 열로 적용하려면 해당 영역(Columns 또는 Rows)에서 선택하십시오. + +새 필드를 추가하려면 원하는 영역에서 "+" 버튼을 클릭한 후 드롭다운 목록에서 이름을 선택하십시오. + +항목을 제거하려면 삭제 버튼("x")을 클릭하십시오. + +![add_remove](assets/add_remove.png) + +테이블에서 값/행/열의 순서를 변경하려면 항목을 원하는 위치로 드래그하십시오. 영역 툴바 목록에서 항목이 왼쪽에 위치할수록 테이블 내 우선순위와 위치가 높아집니다. + +![priority](assets/priority.png) + +테이블 열의 모든 데이터에 적용할 연산을 설정하려면 **Values** 영역에서 원하는 필드의 값 연산을 클릭한 후 목록에서 필요한 옵션을 선택하십시오. + +![operations](assets/operations.png) + +### 필터 {#filters} + +필터는 모든 영역의 각 필드에 대해 드롭다운 목록으로 표시됩니다. Pivot은 다음 조건 유형의 필터링을 제공합니다: + +- 텍스트 값: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith +- 숫자 값: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains, begins with, not begins with, ends with, not ends with +- 날짜 유형: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween + +테이블에서 데이터를 필터링하려면 원하는 영역의 항목에서 필터 아이콘을 클릭한 후 연산자를 선택하고 필터링 기준값을 설정한 다음 **적용**을 클릭하십시오. 필터링이 적용된 필드에는 특별한 필터 아이콘이 표시됩니다. + +![filters](assets/filter.png) + +## 테이블 {#table} + +테이블의 데이터는 구성 패널에서 설정한 대로 표시됩니다. 열 헤더를 클릭하면 열 **정렬**이 활성화됩니다: + +![table](assets/table.png) + +## 다음 단계 {#whats-next} + +이제 Pivot을 애플리케이션에 통합하는 작업을 시작할 수 있습니다. [시작하기](how-to-start.md) 튜토리얼의 안내를 따르십시오. + +위젯 API에서 제공하는 기능을 활용하면 아래 샘플과 같이 더 많은 기능을 갖춘 멋진 피벗 테이블을 구현할 수 있습니다: + + diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/news/migration.md b/i18n/ko/docusaurus-plugin-content-docs/current/news/migration.md new file mode 100644 index 0000000..ff281d0 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/news/migration.md @@ -0,0 +1,57 @@ +--- +sidebar_label: 최신 버전으로 마이그레이션 +title: 최신 버전으로 마이그레이션 +description: DHTMLX JavaScript Pivot 라이브러리 문서에서 최신 버전으로의 마이그레이션 방법을 알아볼 수 있습니다. 개발자 가이드와 API 레퍼런스를 탐색하고, 코드 예제 및 라이브 데모를 사용해 보세요. DHTMLX Pivot의 무료 30일 평가판을 다운로드할 수 있습니다. +--- + +# 최신 버전으로 마이그레이션 + +## 2.0 -> 2.1 + +- `tableShape` 속성의 `sizes` 객체에 있는 `colWidth` 파라미터가 `columnWidth`로 이름이 변경되었습니다. + +## 1.5 -> 2.0 + +이 변경 사항 목록은 이전 버전인 Pivot 1.5에서 완전히 새롭게 개선된 Pivot 2.0으로 마이그레이션하는 데 도움을 드립니다. + +:::note +[v.1.5에서의 데이터 마이그레이션을 위한 변환기](https://snippet.dhtmlx.com/s4sfdhq4) 를 확인하세요. +::: + +### 변경된 API {#changed-api} + +#### 속성 {#properties} + +새 속성은 이전 속성을 완전히 대체하지 않지만 더 확장된 기능을 제공합니다. + +- [fieldList](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldlist_config.html) -> [fields](api/config/fields-property.md) +- [fields](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fields_config.html) -> [config](api/config/config-property.md) +- [mark](https://docs.dhtmlx.com/pivot/1-5/api__pivot_mark_config.html) -> [tableShape](api/config/tableshape-property.md) 속성의 `marks` 파라미터 +- [types](https://docs.dhtmlx.com/pivot/1-5/api__pivot_types_config.html) -> [methods](api/config/methods-property.md) +- [layout](https://docs.dhtmlx.com/pivot/1-5/api__pivot_layout_config.html) -> [columnShape](api/config/columnshape-property.md), [headerShape](api/config/headershape-property.md), [readonly](api/config/readonly-property.md) +- [customFormat](https://docs.dhtmlx.com/pivot/1-5/api__pivot_customformat_config.html) -> [predicates](api/config/predicates-property.md) - 데이터를 위한 사용자 정의 전처리 함수 + +#### 이벤트 {#events} + +- [filterApply](https://docs.dhtmlx.com/pivot/1-5/api__pivot_filterapply_event.html) -> [apply-filter](api/events/apply-filter-event.md) +- [fieldClick](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldclick_event.html) -> 동일한 이벤트는 없지만 [update-field](api/events/update-field-event.md) 를 참조할 수 있습니다. + +### 제거된 API {#removed-api} + +- [버전 1.5의 메서드](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_methods.html) 는 더 이상 사용되지 않으며, 새로운 메서드는 여기서 확인할 수 있습니다: [메서드](api/overview/main-overview.md#pivot-methods) +- [Pivot 1.5 이벤트](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_events.html) (`change`, `fieldClick`, `applyButtonClick`)는 Pivot 2.0에서 더 이상 사용할 수 없지만, 새 버전에서 더 확장된 기능을 제공합니다([Pivot 이벤트](api/overview/events-overview.md) 참조). + +### 중요 기능 {#important-features} + +- 데이터 내보내기: [이전 내보내기 옵션](https://docs.dhtmlx.com/pivot/1-5/guides__export.html) -> [새 내보내기 옵션](guides/exporting-data.md) +- 정렬: [필드 정렬](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringfields) -> [데이터 정렬](guides/working-with-data.md#sorting-data) +- 트리 모드: [gridMode](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#gridmode) -> [트리 모드 활성화](guides/configuration.md#enabling-the-tree-mode) +- 날짜 형식: [날짜 필드 구성](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringdatefields) -> +[날짜 형식 설정](guides/localization.md#date-formatting) +- 커스터마이징: + - [셀 서식 지정](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#conditionalformattingofcells) -> [셀 스타일](guides/stylization.md#cell-style) + - [헤더 템플릿](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforheaders) -> + [헤더에 템플릿 적용](guides/configuration.md#applying-templates-to-headers) + - [셀 템플릿](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforcells) -> + [셀에 템플릿 적용](guides/configuration.md#applying-templates-to-cells) +- 필터링: [필터 조작](https://docs.dhtmlx.com/pivot/1-5/guides__using_filters.html) -> [데이터 필터링](guides/working-with-data.md#filtering-data) diff --git a/i18n/ko/docusaurus-plugin-content-docs/current/news/whats-new.md b/i18n/ko/docusaurus-plugin-content-docs/current/news/whats-new.md new file mode 100644 index 0000000..9842221 --- /dev/null +++ b/i18n/ko/docusaurus-plugin-content-docs/current/news/whats-new.md @@ -0,0 +1,114 @@ +--- +sidebar_label: 새로운 기능 +title: 새로운 기능 +description: DHTMLX JavaScript UI 라이브러리 문서에서 DHTMLX Pivot의 새로운 기능과 릴리스 이력을 확인하세요. 개발자 가이드와 API 레퍼런스를 살펴보고, 코드 예제와 라이브 데모를 체험해 보세요. DHTMLX Pivot 무료 30일 평가판도 다운로드할 수 있습니다. +--- + +# 새로운 기능 {#whats-new} + +이전 버전에서 Pivot을 업그레이드하는 경우 자세한 내용은 [최신 버전으로의 마이그레이션](news/migration.md) 을 확인하세요. + +## 버전 2.1.1 {#version-211} + +2026년 6월 10일 릴리스 + +### 수정 사항 {#fixes} + +- 행 필터를 값이 누락되거나 비어 있는 데이터셋에 적용할 때 "getMonth" 오류가 발생하는 문제 + +## 버전 2.1 {#version-21} + +2025년 5월 6일 릴리스 + +### 새로운 기능 {#new-functionality} + +- [오른쪽 열 고정 기능](guides/configuration.md#freezing-columns-on-the-right) +- 숫자 값에 대한 [기본 정렬](guides/stylization.md#specific-css-classes) 및 [로케일 기반 서식](guides/localization.md#number-formatting) +- [`fields`](api/config/fields-property.md) 속성에 추가된 `format`을 통해 날짜 및 숫자 필드에 대한 [사용자 정의 숫자 형식 정의 기능](guides/working-with-data.md#applying-formats-to-fields) +- [`tableShape`](api/config/tableshape-property.md) 및 [`headerShape`](api/config/headershape-property.md) 속성의 `cellStyle` 매개변수를 통해 [헤더 및 테이블 셀 스타일 지정 기능](guides/stylization.md#cell-style) +- 헤더 및 열 객체의 `cell` 속성으로 템플릿을 정의하여 [`pivot.template`](api/helpers/template.md) 헬퍼를 통해 헤더 및 테이블 셀에 HTML 콘텐츠를 삽입하는 기능([render-table](api/events/render-table-event.md) 이벤트를 가로채어 테이블 사용자 정의) +- [Excel 및 CSV 내보내기 설정 개선](guides/exporting-data.md): + - "xlsx" 형식의 경우, 날짜 및 숫자 필드는 기본 형식 또는 [`fields`](api/config/fields-property.md) 속성으로 정의된 형식의 원시 값으로 내보내집니다 + - 파일 및 시트 이름 정의와 내보낸 파일에서 헤더/푸터 제외 기능 + - 내보낸 셀에 스타일 및 템플릿 추가 기능 +- [외부 입력을 통한 데이터 필터링 기능](api/table/filter-rows.md) +- 셀 탐색을 위한 시각적 프레임 +- [프레임워크와의 통합](/category/integration-with-frameworks) + +### 새로운 API {#new-api} + +- [`tableShape`](api/config/tableshape-property.md)의 `split` 객체 내 `right` 설정 +- [`tableShape`](api/config/tableshape-property.md) 및 [`headerShape`](api/config/headershape-property.md) 속성 내 `cellStyle` 설정 +- [`fields`](api/config/fields-property.md) 배열 내 `format` 설정 +- 내부 Table의 [`filter-rows`](api/table/filter-rows.md) 이벤트 +- 테이블 셀에 HTML 콘텐츠를 정의하는 [`pivot.template`](api/helpers/template.md) + +### 수정 사항 {#fixes-21} + +- 합계 열이 정렬되지 않는 문제 +- 앞에 0이 있는 문자열 값이 내보내기 중 숫자로 변환되는 문제 +- Predicate 템플릿이 행/열에 적용되지 않는 문제 +- 특수한 경우 resize observer 오류 + +### 주요 변경 사항 {#breaking-changes} + +- `tableShape` 속성의 `sizes` 객체 내 `colWidth` 매개변수가 `columnWidth`로 이름 변경됨 + +## 버전 2.0.3 {#version-203} + +2024년 11월 29일 릴리스 + +### 수정 사항 {#fixes-203} + +- 트리 구조를 Excel/CSV로 내보낼 때 최상위 브랜치만 포함되는 문제 +- autowidth가 적용된 내보낸 열이 결과 Excel 파일에서 너무 좁게 표시되는 문제 +- 필터 팝업의 위치가 잘못 표시되는 문제 +- `setConfig` 메서드로 구성을 변경한 후 동작이 올바르지 않은 문제 +- 더 정확한 타입 정의 + +## 버전 2.0.2 {#version-202} + +2024년 10월 22일 릴리스 + +### 수정 사항 {#fixes-202} + +- `columnShape` 타입 정의 +- 올바른 패키지 내용 + +## 버전 2.0 {#version-20} + +2024년 8월 26일 릴리스 + +[블로그 페이지](https://dhtmlx.com/blog/) 에서 이번 릴리스 리뷰를 확인하세요. + +### 주요 변경 사항 {#breaking-change} + +:::note +버전 1.5의 API는 API v.2.0과 호환되지 않습니다. +::: + +새 버전으로의 마이그레이션 팁은 [마이그레이션](news/migration.md) 페이지를 확인하세요. + +### 새로운 기능 {#new-functionality-20} + +- Pivot 2.0은 대용량 데이터셋 렌더링 및 생성 속도가 빠릅니다 ([샘플](https://snippet.dhtmlx.com/e6qwqrys)) +- [`columnShape`](api/config/columnshape-property.md) 속성을 통해 열의 모양과 동작을 구성하는 다음 새 기능을 사용할 수 있습니다: + - **autoWidth** 계산에 처리할 maxRows를 설정하는 기능이 포함된 **autowidth** 설정 ([샘플](https://snippet.dhtmlx.com/tn1yw14m)) + - 열 너비 계산 시 동일한 데이터의 각 필드를 한 번만 분석하는 **firstOnly** 기능 (기본값) +- 이제 [`headerShape`](api/config/headershape-property.md) 속성을 사용하여 헤더의 모양과 동작을 구성할 수 있습니다: + - 헤더 텍스트에 템플릿 적용 ([샘플](https://snippet.dhtmlx.com/g89r9ryw)) + - 텍스트 방향 변경 ([샘플](https://snippet.dhtmlx.com/4qroi8ka)) + - 열 접기 가능하게 만들기 ([샘플](https://snippet.dhtmlx.com/pt2ljmcm)) +- [`tableShape`](api/config/tableshape-property.md) 속성을 통해 테이블의 모양과 크기를 구성할 수 있습니다: + - 행, 헤더, 푸터 높이 구성: rowHeight, headerHeight, footerHeight ([테이블 크기 조정](guides/configuration.md#resizing-the-table)) + - `tableShape` 속성의 **totalColumn** 매개변수를 통해 열뿐만 아니라 행에 대해서도 합계 값 생성 ([샘플](https://snippet.dhtmlx.com/f0ag0t9t)) + - 테이블 뷰에서 중복 값 숨기기([`tableShape`](api/config/tableshape-property.md) 속성의 **cleanRows** 매개변수) + - 스크롤 시 왼쪽 열을 고정하여 정적으로 유지 ([샘플](https://snippet.dhtmlx.com/lahf729o)) + - 모든 행 펼치기 또는 접기 ([샘플](https://snippet.dhtmlx.com/i4mi6ejn)) +- 데이터 집계에 더 많은 기능이 추가되었습니다: + - [불러온 데이터 제한](guides/working-with-data.md#limiting-loaded-data) + - 더 많은 [데이터 연산](guides/working-with-data.md#applying-maths-methods) 사용 가능 + - [Predicate를 사용한 데이터 처리](guides/working-with-data.md#processing-data-with-predicates) - 데이터에 사용자 정의 전처리 함수 적용 + - [로케일을 통한 날짜 형식 설정](guides/localization.md#date-formatting) +- 새로운 메서드 추가: [`getTable()`](api/methods/gettable-method.md), [`setConfig()`](api/methods/setconfig-method.md), [`setLocale()`](api/methods/setlocale-method.md), [`showConfigPanel()`](api/methods/showconfigpanel-method.md) +- 새로운 이벤트 추가: [`add-field`](api/events/add-field-event.md), [`delete-field`](api/events/delete-field-event.md), [`open-filter`](api/events/open-filter-event.md), [`render-table`](api/events/render-table-event.md), [`move-field`](api/events/move-field-event.md), [`show-config-panel`](api/events/show-config-panel-event.md), [`show-config-panel`](api/events/show-config-panel-event.md), [`update-config`](api/events/update-config-event.md), [`update-field`](api/events/update-field-event.md). diff --git a/i18n/ko/docusaurus-theme-classic/footer.json b/i18n/ko/docusaurus-theme-classic/footer.json new file mode 100644 index 0000000..22127e5 --- /dev/null +++ b/i18n/ko/docusaurus-theme-classic/footer.json @@ -0,0 +1,62 @@ +{ + "link.title.Development center": { + "message": "개발 센터", + "description": "The title of the footer links column with title=Development center in the footer" + }, + "link.title.Community": { + "message": "커뮤니티", + "description": "The title of the footer links column with title=Community in the footer" + }, + "link.title.Company": { + "message": "회사", + "description": "The title of the footer links column with title=Company in the footer" + }, + "link.item.label.Download JS Pivot": { + "message": "JS Pivot 다운로드", + "description": "The label of footer link with label=Download JS Pivot linking to https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml" + }, + "link.item.label.Examples": { + "message": "예제", + "description": "The label of footer link with label=Examples linking to https://snippet.dhtmlx.com/mhymus00?tag=pivot" + }, + "link.item.label.Blog": { + "message": "블로그", + "description": "The label of footer link with label=Blog linking to https://dhtmlx.com/blog/tag/pivot/" + }, + "link.item.label.Forum": { + "message": "포럼", + "description": "The label of footer link with label=Forum linking to https://forum.dhtmlx.com/c/pivot/16" + }, + "link.item.label.GitHub": { + "message": "GitHub", + "description": "The label of footer link with label=GitHub linking to https://github.com/DHTMLX" + }, + "link.item.label.Youtube": { + "message": "유튜브", + "description": "The label of footer link with label=Youtube linking to https://www.youtube.com/user/dhtmlx" + }, + "link.item.label.Facebook": { + "message": "페이스북", + "description": "The label of footer link with label=Facebook linking to https://www.facebook.com/dhtmlx" + }, + "link.item.label.Twitter": { + "message": "트위터", + "description": "The label of footer link with label=Twitter linking to https://twitter.com/dhtmlx" + }, + "link.item.label.Linkedin": { + "message": "링크드인", + "description": "The label of footer link with label=Linkedin linking to https://www.linkedin.com/groups/3345009/" + }, + "link.item.label.About us": { + "message": "회사 소개", + "description": "The label of footer link with label=About us linking to https://dhtmlx.com/docs/company.shtml" + }, + "link.item.label.Contact us": { + "message": "문의하기", + "description": "The label of footer link with label=Contact us linking to https://dhtmlx.com/docs/contact.shtml" + }, + "link.item.label.Licensing": { + "message": "라이선스", + "description": "The label of footer link with label=Licensing linking to https://dhtmlx.com/docs/products/dhtmlxPivot/#licensing" + } +} diff --git a/i18n/ko/docusaurus-theme-classic/navbar.json b/i18n/ko/docusaurus-theme-classic/navbar.json new file mode 100644 index 0000000..3edd506 --- /dev/null +++ b/i18n/ko/docusaurus-theme-classic/navbar.json @@ -0,0 +1,26 @@ +{ + "title": { + "message": "자바스크립트 Pivot 문서", + "description": "The title in the navbar" + }, + "logo.alt": { + "message": "DHTMLX 자바스크립트 Pivot 로고", + "description": "The alt text of navbar logo" + }, + "item.label.Examples": { + "message": "예제", + "description": "Navbar item with label Examples" + }, + "item.label.Forum": { + "message": "포럼", + "description": "Navbar item with label Forum" + }, + "item.label.Support": { + "message": "지원", + "description": "Navbar item with label Support" + }, + "item.label.Download": { + "message": "다운로드", + "description": "Navbar item with label Download" + } +} diff --git a/i18n/ru/code.json b/i18n/ru/code.json new file mode 100644 index 0000000..80e6aa6 --- /dev/null +++ b/i18n/ru/code.json @@ -0,0 +1,364 @@ +{ + "theme.ErrorPageContent.title": { + "message": "Эта страница упала.", + "description": "The title of the fallback page when the page crashed" + }, + "theme.BackToTopButton.buttonAriaLabel": { + "message": "Прокрутить обратно наверх", + "description": "The ARIA label for the back to top button" + }, + "theme.blog.archive.title": { + "message": "Архив", + "description": "The page & hero title of the blog archive page" + }, + "theme.blog.archive.description": { + "message": "Архив", + "description": "The page & hero description of the blog archive page" + }, + "theme.blog.paginator.navAriaLabel": { + "message": "Навигация по списку страниц блога", + "description": "The ARIA label for the blog pagination" + }, + "theme.blog.paginator.newerEntries": { + "message": "Новые записи", + "description": "The label used to navigate to the newer blog posts page (previous page)" + }, + "theme.blog.paginator.olderEntries": { + "message": "Старые записи", + "description": "The label used to navigate to the older blog posts page (next page)" + }, + "theme.blog.post.paginator.navAriaLabel": { + "message": "Навигация по страницам записей блога", + "description": "The ARIA label for the blog posts pagination" + }, + "theme.blog.post.paginator.newerPost": { + "message": "Новая запись", + "description": "The blog post button label to navigate to the newer/previous post" + }, + "theme.blog.post.paginator.olderPost": { + "message": "Старая запись", + "description": "The blog post button label to navigate to the older/next post" + }, + "theme.tags.tagsPageLink": { + "message": "Посмотреть все теги", + "description": "The label of the link targeting the tag list page" + }, + "theme.colorToggle.ariaLabel.mode.system": { + "message": "системный режим", + "description": "The name for the system color mode" + }, + "theme.colorToggle.ariaLabel.mode.light": { + "message": "светлый режим", + "description": "The name for the light color mode" + }, + "theme.colorToggle.ariaLabel.mode.dark": { + "message": "темный режим", + "description": "The name for the dark color mode" + }, + "theme.colorToggle.ariaLabel": { + "message": "Переключить между темным и светлым режимом (сейчас {mode})", + "description": "The ARIA label for the color mode toggle" + }, + "theme.docs.breadcrumbs.navAriaLabel": { + "message": "Хлебные крошки", + "description": "The ARIA label for the breadcrumbs" + }, + "theme.docs.DocCard.categoryDescription.plurals": { + "message": "1 элемент|{count} элемента|{count} элементов", + "description": "The default description for a category card in the generated index about how many items this category includes" + }, + "theme.docs.paginator.navAriaLabel": { + "message": "Страницы документации", + "description": "The ARIA label for the docs pagination" + }, + "theme.docs.paginator.previous": { + "message": "Предыдущая", + "description": "The label used to navigate to the previous doc" + }, + "theme.docs.paginator.next": { + "message": "Следующая", + "description": "The label used to navigate to the next doc" + }, + "theme.docs.tagDocListPageTitle.nDocsTagged": { + "message": "Один документ отмечен|{count} документа отмечены|{count} документов отмечены", + "description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.docs.tagDocListPageTitle": { + "message": "{nDocsTagged} с \"{tagName}\"", + "description": "The title of the page for a docs tag" + }, + "theme.docs.versionBadge.label": { + "message": "Версия: {versionLabel}" + }, + "theme.docs.versions.unreleasedVersionLabel": { + "message": "Это неопубликованная документация для {siteTitle} версии {versionLabel}.", + "description": "The label used to tell the user that he's browsing an unreleased doc version" + }, + "theme.docs.versions.unmaintainedVersionLabel": { + "message": "Это документация для {siteTitle} {versionLabel}, которая больше не поддерживается активно.", + "description": "The label used to tell the user that he's browsing an unmaintained doc version" + }, + "theme.docs.versions.latestVersionSuggestionLabel": { + "message": "Для актуальной документации смотрите {latestVersionLink} ({versionLabel}).", + "description": "The label used to tell the user to check the latest version" + }, + "theme.docs.versions.latestVersionLinkLabel": { + "message": "последняя версия", + "description": "The label used for the latest version suggestion link label" + }, + "theme.common.editThisPage": { + "message": "Редактировать эту страницу", + "description": "The link label to edit the current page" + }, + "theme.common.headingLinkTitle": { + "message": "Прямая ссылка на {heading}", + "description": "Title for link to heading" + }, + "theme.lastUpdated.atDate": { + "message": " {date}", + "description": "The words used to describe on which date a page has been last updated" + }, + "theme.lastUpdated.byUser": { + "message": " пользователем {user}", + "description": "The words used to describe by who the page has been last updated" + }, + "theme.lastUpdated.lastUpdatedAtBy": { + "message": "Последнее обновление{atDate}{byUser}", + "description": "The sentence used to display when a page has been last updated, and by who" + }, + "theme.navbar.mobileVersionsDropdown.label": { + "message": "Версии", + "description": "The label for the navbar versions dropdown on mobile view" + }, + "theme.NotFound.title": { + "message": "Страница не найдена", + "description": "The title of the 404 page" + }, + "theme.tags.tagsListLabel": { + "message": "Теги:", + "description": "The label alongside a tag list" + }, + "theme.AnnouncementBar.closeButtonAriaLabel": { + "message": "Закрыть", + "description": "The ARIA label for close button of announcement bar" + }, + "theme.admonition.caution": { + "message": "осторожно", + "description": "The default label used for the Caution admonition (:::caution)" + }, + "theme.admonition.danger": { + "message": "опасность", + "description": "The default label used for the Danger admonition (:::danger)" + }, + "theme.admonition.info": { + "message": "информация", + "description": "The default label used for the Info admonition (:::info)" + }, + "theme.admonition.note": { + "message": "заметка", + "description": "The default label used for the Note admonition (:::note)" + }, + "theme.admonition.tip": { + "message": "совет", + "description": "The default label used for the Tip admonition (:::tip)" + }, + "theme.admonition.warning": { + "message": "предупреждение", + "description": "The default label used for the Warning admonition (:::warning)" + }, + "theme.blog.sidebar.navAriaLabel": { + "message": "Навигация по последним записям блога", + "description": "The ARIA label for recent posts in the blog sidebar" + }, + "theme.DocSidebarItem.expandCategoryAriaLabel": { + "message": "Развернуть категорию боковой панели '{label}'", + "description": "The ARIA label to expand the sidebar category" + }, + "theme.DocSidebarItem.collapseCategoryAriaLabel": { + "message": "Свернуть категорию боковой панели '{label}'", + "description": "The ARIA label to collapse the sidebar category" + }, + "theme.IconExternalLink.ariaLabel": { + "message": "(открывается в новой вкладке)", + "description": "The ARIA label for the external link icon" + }, + "theme.NavBar.navAriaLabel": { + "message": "Главная", + "description": "The ARIA label for the main navigation" + }, + "theme.navbar.mobileLanguageDropdown.label": { + "message": "Языки", + "description": "The label for the mobile language switcher dropdown" + }, + "theme.NotFound.p1": { + "message": "Мы не смогли найти то, что вы искали.", + "description": "The first paragraph of the 404 page" + }, + "theme.NotFound.p2": { + "message": "Пожалуйста, свяжитесь с владельцем сайта, который направил вас на исходный URL, и сообщите им, что их ссылка не работает.", + "description": "The 2nd paragraph of the 404 page" + }, + "theme.TOCCollapsible.toggleButtonLabel": { + "message": "На этой странице", + "description": "The label used by the button on the collapsible TOC component" + }, + "theme.blog.post.readMore": { + "message": "Читать далее", + "description": "The label used in blog post item excerpts to link to full blog posts" + }, + "theme.blog.post.readMoreLabel": { + "message": "Читать далее о {title}", + "description": "The ARIA label for the link to full blog posts from excerpts" + }, + "theme.blog.post.readingTime.plurals": { + "message": "Одна минута чтения|{readingTime} минуты чтения|{readingTime} минут чтения", + "description": "Pluralized label for \"{readingTime} min read\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.CodeBlock.copy": { + "message": "Копировать", + "description": "The copy button label on code blocks" + }, + "theme.CodeBlock.copied": { + "message": "Скопировано", + "description": "The copied button label on code blocks" + }, + "theme.CodeBlock.copyButtonAriaLabel": { + "message": "Скопировать код в буфер обмена", + "description": "The ARIA label for copy code blocks button" + }, + "theme.CodeBlock.wordWrapToggle": { + "message": "Переключить перенос слов", + "description": "The title attribute for toggle word wrapping button of code block lines" + }, + "theme.docs.breadcrumbs.home": { + "message": "Главная страница", + "description": "The ARIA label for the home page in the breadcrumbs" + }, + "theme.docs.sidebar.collapseButtonTitle": { + "message": "Свернуть боковую панель", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.collapseButtonAriaLabel": { + "message": "Свернуть боковую панель", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.navAriaLabel": { + "message": "Боковая панель документации", + "description": "The ARIA label for the sidebar navigation" + }, + "theme.docs.sidebar.closeSidebarButtonAriaLabel": { + "message": "Закрыть панель навигации", + "description": "The ARIA label for close button of mobile sidebar" + }, + "theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": { + "message": "← Вернуться в главное меню", + "description": "The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)" + }, + "theme.docs.sidebar.toggleSidebarButtonAriaLabel": { + "message": "Переключить панель навигации", + "description": "The ARIA label for hamburger menu button of mobile navigation" + }, + "theme.navbar.mobileDropdown.collapseButton.expandAriaLabel": { + "message": "Развернуть выпадающий список", + "description": "The ARIA label of the button to expand the mobile dropdown navbar item" + }, + "theme.navbar.mobileDropdown.collapseButton.collapseAriaLabel": { + "message": "Свернуть выпадающий список", + "description": "The ARIA label of the button to collapse the mobile dropdown navbar item" + }, + "theme.docs.sidebar.expandButtonTitle": { + "message": "Развернуть боковую панель", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.docs.sidebar.expandButtonAriaLabel": { + "message": "Развернуть боковую панель", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.SearchPage.existingResultsTitle": { + "message": "Результаты поиска для \"{query}\"", + "description": "The search page title for non-empty query" + }, + "theme.SearchPage.emptyResultsTitle": { + "message": "Поиск в документации", + "description": "The search page title for empty query" + }, + "theme.SearchPage.searchContext.everywhere": { + "message": "Везде" + }, + "theme.SearchPage.documentsFound.plurals": { + "message": "Найден один документ|Найдено {count} документа|Найдено {count} документов", + "description": "Pluralized label for \"{count} documents found\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.SearchPage.noResultsText": { + "message": "Результаты не найдены", + "description": "The paragraph for empty search result" + }, + "theme.SearchBar.noResultsText": { + "message": "Нет результатов" + }, + "theme.SearchBar.seeAllOutsideContext": { + "message": "Показать все результаты за пределами \"{context}\"" + }, + "theme.SearchBar.searchInContext": { + "message": "Показать все результаты в \"{context}\"" + }, + "theme.SearchBar.seeAll": { + "message": "Посмотреть все {count} результатов" + }, + "theme.SearchBar.label": { + "message": "Поиск", + "description": "The ARIA label and placeholder for search button" + }, + "theme.blog.post.plurals": { + "message": "Одна запись|{count} записи|{count} записей", + "description": "Pluralized label for \"{count} posts\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.blog.tagTitle": { + "message": "{nPosts} отмечены тегом \"{tagName}\"", + "description": "The title of the page for a blog tag" + }, + "theme.blog.author.pageTitle": { + "message": "{authorName} - {nPosts}", + "description": "The title of the page for a blog author" + }, + "theme.blog.authorsList.pageTitle": { + "message": "Авторы", + "description": "The title of the authors page" + }, + "theme.blog.authorsList.viewAll": { + "message": "Посмотреть всех авторов", + "description": "The label of the link targeting the blog authors page" + }, + "theme.blog.author.noPosts": { + "message": "Этот автор еще не написал ни одной записи.", + "description": "The text for authors with 0 blog post" + }, + "theme.contentVisibility.unlistedBanner.title": { + "message": "Неперечисленная страница", + "description": "The unlisted content banner title" + }, + "theme.contentVisibility.unlistedBanner.message": { + "message": "Эта страница не перечислена. Поисковые системы не будут индексировать ее, и только пользователи с прямой ссылкой могут получить к ней доступ.", + "description": "The unlisted content banner message" + }, + "theme.contentVisibility.draftBanner.title": { + "message": "Черновик страницы", + "description": "The draft content banner title" + }, + "theme.contentVisibility.draftBanner.message": { + "message": "Эта страница является черновиком. Она будет видна только в разработке и исключена из продакшн сборки.", + "description": "The draft content banner message" + }, + "theme.ErrorPageContent.tryAgain": { + "message": "Попробовать снова", + "description": "The label of the button to try again rendering when the React error boundary captures an error" + }, + "theme.common.skipToMainContent": { + "message": "Перейти к основному содержимому", + "description": "The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation" + }, + "theme.tags.tagsPageTitle": { + "message": "Теги", + "description": "The title of the tag list page" + } +} diff --git a/i18n/ru/docusaurus-plugin-content-blog/options.json b/i18n/ru/docusaurus-plugin-content-blog/options.json new file mode 100644 index 0000000..e90f442 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-blog/options.json @@ -0,0 +1,14 @@ +{ + "title": { + "message": "Блог", + "description": "The title for the blog used in SEO" + }, + "description": { + "message": "Блог", + "description": "The description for the blog used in SEO" + }, + "sidebar.title": { + "message": "Последние записи", + "description": "The label for the left sidebar" + } +} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current.json b/i18n/ru/docusaurus-plugin-content-docs/current.json new file mode 100644 index 0000000..ac796cf --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current.json @@ -0,0 +1,70 @@ +{ + "version.label": { + "message": "Следующий", + "description": "The label for version current" + }, + "sidebar.docs.category.What's new and migration": { + "message": "Что нового и миграция", + "description": "The label for category 'What's new and migration' in sidebar 'docs'" + }, + "sidebar.docs.category.What's new and migration.link.generated-index.title": { + "message": "Что нового и миграция", + "description": "The generated-index page title for category 'What's new and migration' in sidebar 'docs'" + }, + "sidebar.docs.category.API": { + "message": "API", + "description": "The label for category 'API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot methods": { + "message": "Методы Pivot", + "description": "The label for category 'Pivot methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API": { + "message": "Внутренний API Pivot", + "description": "The label for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API.link.generated-index.title": { + "message": "Обзор внутреннего API", + "description": "The generated-index page title for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Event Bus methods": { + "message": "Методы Event Bus", + "description": "The label for category 'Event Bus methods' in sidebar 'docs'" + }, + "sidebar.docs.category.State methods": { + "message": "Методы состояния", + "description": "The label for category 'State methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot events": { + "message": "События Pivot", + "description": "The label for category 'Pivot events' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot properties": { + "message": "Свойства Pivot", + "description": "The label for category 'Pivot properties' in sidebar 'docs'" + }, + "sidebar.docs.category.Table events": { + "message": "События Table", + "description": "The label for category 'Table events' in sidebar 'docs'" + }, + "sidebar.docs.category.Helpers": { + "message": "Хелперы", + "description": "The label for category 'Helpers' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks": { + "message": "Интеграция с фреймворками", + "description": "The label for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks.link.generated-index.title": { + "message": "Интеграция с фреймворками", + "description": "The generated-index page title for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides": { + "message": "Руководства", + "description": "The label for category 'Guides' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides.link.generated-index.title": { + "message": "Руководства", + "description": "The generated-index page title for category 'Guides' in sidebar 'docs'" + } +} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/.sync b/i18n/ru/docusaurus-plugin-content-docs/current/.sync new file mode 100644 index 0000000..a5b7004 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/.sync @@ -0,0 +1 @@ +44e03f98ab2c058ad802e8e3e08c689d0efdde69 diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md new file mode 100644 index 0000000..d0fe77a --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md @@ -0,0 +1,82 @@ +--- +sidebar_label: columnShape +title: columnShape Config +description: Вы можете узнать о конфигурации columnShape в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, просматривайте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# columnShape + +### Описание {#description} + +@short: Необязательный. Настраивает внешний вид и поведение колонок Pivot + +### Использование {#usage} + +~~~jsx +columnShape?: { + sort?: boolean, + width?: { + [field: string]: number + }, + autoWidth?: { + columns: { + [field: string]: boolean + }, + auto?: boolean | "header" | "data", + maxRows?: number, + firstOnly?: boolean + } +}; +~~~ + +### Параметры {#parameters} + +- `sort` - (необязательный) если **true** (по умолчанию), сортировка включена в интерфейсе по клику на заголовок колонки; если **false**, сортировка отключена +- `width` - (необязательный) определяет ширину колонки; это объект, где каждый ключ — идентификатор поля, а значение — ширина колонки в пикселях +- `autoWidth` - (необязательный) объект, определяющий, как ширина колонки должна рассчитываться автоматически. По умолчанию используется 20 строк, а ширина рассчитывается на основе заголовка и данных, при этом каждое поле анализируется только один раз. Параметры объекта следующие: + - `columns` - (обязательный) объект, где каждый ключ — идентификатор поля, а булево значение определяет, должна ли ширина колонки рассчитываться автоматически + - `auto` - (необязательный) если установлено **header**, подстраивает ширину под текст заголовка; если установлено **data**, подстраивает ширину под ячейку с наибольшим содержимым; если установлено **true**, ширина подстраивается под содержимое как заголовков, так и ячеек. + Если autoWidth установлено в **false**, применяется значение `width` или значение `columnWidth` из свойства [`tableShape`](api/config/tableshape-property.md). + - `maxRows` - (необязательный) количество строк, обрабатываемых при расчёте autoWidth + - `firstOnly` - (необязательный) если установлено **true** (по умолчанию), каждое поле с одинаковыми данными анализируется только один раз для расчёта ширины колонки; в случае нескольких колонок на основе одних и тех же данных (например, поле *oil* с операцией *count* и поле *oil* с операцией *sum*) анализируются только данные первой колонки, остальные наследуют её ширину + +## Пример {#example} + +~~~jsx {18-31} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + autoWidth: { + // рассчитать ширину колонки для этих полей + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + auto: true, + // анализировать все поля + firstOnly: false + } + } +}); +~~~ + +**Связанные примеры**: +- [Pivot 2. Автоматическая ширина. Подстройка колонок под содержимое](https://snippet.dhtmlx.com/tn1yw14m) +- [Pivot 2. Установка ширины колонок](https://snippet.dhtmlx.com/ceu34kkn) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/config-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/config-property.md new file mode 100644 index 0000000..656d181 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/config-property.md @@ -0,0 +1,146 @@ +--- +sidebar_label: config +title: config Config +description: Вы можете узнать о свойстве config в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства разработчика и справочник по API, попробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# config + +### Описание {#description} + +@short: Опциональный. Определяет структуру таблицы Pivot и способ агрегации данных + +### Использование {#usage} + +~~~jsx +config?: { + rows?: string | {field: string, method?: string}[], + columns?: string | {field: string, method?: string}[], + values?: string | {field: string, method?: string}[], + filters?: {} +}; +~~~ + +### Параметры {#parameters} + +Параметры `config` используются для определения того, какие поля будут применяться в качестве строк и столбцов, а также какие дополнительные методы агрегации данных должны применяться к строкам/столбцам. + +- `rows` - (опциональный) определяет строки таблицы Pivot. Значение по умолчанию — пустой массив. Может быть строкой, представляющей идентификатор одного поля, или объектом с идентификатором поля и методом извлечения данных; параметры объекта следующие: + - `field` - (обязательный) идентификатор поля + - `method` - (опциональный) определяет метод агрегации данных в поле; по умолчанию доступны методы для полей с данными времени: "year", "quarter", "month", "week", "day", "hour", "minute", которые группируют данные соответствующим образом; здесь также можно указать имя пользовательского метода ([см. `predicates`](api/config/predicates-property.md)) для поля любого типа данных +- `columns` - (опциональный) определяет столбцы таблицы Pivot. По умолчанию — пустой массив. Может быть идентификатором одного поля или объектом с идентификатором поля и методом извлечения данных; параметры объекта следующие: + - `field` - (обязательный) идентификатор поля + - `method` - (опциональный) определяет метод обработки данных (для полей с данными времени). + По умолчанию методы доступны для полей с данными времени (тип **date**) со следующими значениями: "year", "quarter", "month", "week", "day", "hour", "minute". Здесь также можно указать имя пользовательского метода ([см. `predicates`](api/config/predicates-property.md)) для поля любого типа данных +- `values` - (опциональный) определяет агрегацию данных для ячеек таблицы Pivot. По умолчанию — пустой массив. Каждый элемент может быть строкой, представляющей идентификатор поля данных и метод агрегации, или объектом, содержащим идентификатор поля и метод агрегации данных. Параметры объекта следующие: + - `field` - (обязательный) идентификатор поля + - `method` - (обязательный) определяет метод извлечения данных; описание типов методов см. в разделе [Применение методов](guides/working-with-data.md#default-methods) + +
+ +Варианты определения values + +Можно определить `values` одним из двух равнозначных способов: +- первый вариант — строка, представляющая идентификатор поля +- второй вариант — объект, содержащий идентификатор поля и метод агрегации данных + +### Пример {#example} + +~~~jsx +values: [ + "sum(sales)", // первый вариант + { field: "sales", method: "sum" }, // второй вариант +] +~~~ + +
+ +- `filters` - (опциональный) определяет способ фильтрации данных в таблице; это объект с идентификаторами полей и правилом фильтрации. Значение по умолчанию — пустой объект. Параметры объекта следующие: + - `field` - (опциональный) ключ фильтра, который является идентификатором поля или массивом идентификаторов с критериями фильтрации: + - `equal` - (опциональный) принимает числа, строки и значения Date + - `notEqual` - (опциональный) принимает числа, строки и значения Date + - `greater` - (опциональный) принимает числа и значения Date + - `greaterOrEqual` - (опциональный) принимает числа и значения Date + - `less` - (опциональный) принимает числа и значения Date + - `lessOrEqual` - принимает числа и значения Date + - `between` - объект со следующими параметрами: + - `start` - Date + - `end` - Date + - `notBetween` - объект со следующими параметрами: + - `start` - Date + - `end` - Date + - `contains` - принимает строки и числа + - `notContains` - принимает строки и числа + - `beginsWith` - принимает строки и числа + - `notBeginsWith` - принимает строки и числа + - `endsWith` - принимает строки и числа + - `notEndsWith` - принимает строки и числа + - `includes` - (опциональный) массив значений для отображения из уже отфильтрованных; доступен для текстовых значений и дат + +:::info +Когда config обрабатывается Pivot, его свойства получают дополнительные данные, и если попытаться вернуть состояние конфигурации через метод [`api.getState()`](api/internal/getstate-method.md), полный объект будет выглядеть следующим образом: + +~~~jsx +interface IParsedField { + id: string, + field: string, + method: string | null, + area: 'rows'|'columns'|'values', + base?: string, + label: string, + type: 'number'|'date'|'text' +} + +interface IParsedConfig { + rows: IParsedField[], + columns: IParsedField[], + values: IParsedField[], + filters: { + [field: string]: number | string | [] | + { [operation: string]: number | string | [] | { start:Date, end: Date} } + } +} +~~~ + +Параметры: + +- `id` - уникальный идентификатор обработанного поля +- `field` - название поля +- `method` - название операции, используемой для агрегации. Метод является опциональным для строк и столбцов, и если указан, действует как предикат и определяет способ предварительной обработки данных поля перед агрегацией. Для values метод является обязательным параметром. +- `area` - область, в которую добавляется поле +- `base` - используется в столбцах и строках для полей с предикатом. Определяет исходное название поля, тогда как название поля формируется по шаблону "field_by_predicate" +- `label` - текстовая метка +- `type` - тип данных +::: + +### Пример {#example-1} + +~~~jsx {4-26} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // фильтр для другого поля ("title") + contains: "A" + } + } + } +}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md new file mode 100644 index 0000000..8f4e45f --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md @@ -0,0 +1,58 @@ +--- +sidebar_label: configPanel +title: Конфигурация configPanel +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о конфигурации configPanel. Изучайте руководства разработчика и справочник по API, пробуйте примеры кода и живые демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# configPanel + +### Описание {#description} + +@short: Необязательный. Управляет видимостью панели конфигурации в интерфейсе + +В интерфейсе панель скрывается/отображается нажатием кнопки **Hide Settings**. + +### Использование {#usage} + +~~~jsx +configPanel?: boolean; +~~~ + +### Параметры {#parameters} + +Свойство может принимать значение **true** или **false**: + +- `true` — по умолчанию, показывает панель конфигурации +- `false` — скрывает панель конфигурации + +## Пример {#example} + +~~~jsx {5} +// Панель конфигурации скрыта при инициализации +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + configPanel: false, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +**Связанный пример**: [Pivot 2.0: Переключение видимости панели конфигурации](https://snippet.dhtmlx.com/1xq1x5bo) + +**Связанные статьи**: +- [Событие `show-config-panel`](api/events/show-config-panel-event.md) +- [Метод `showConfigPanel()`](api/methods/showconfigpanel-method.md) +- [Управление видимостью панели конфигурации](guides/configuration.md#controlling-visibility-of-configuration-panel) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/data-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/data-property.md new file mode 100644 index 0000000..d1f4b73 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/data-property.md @@ -0,0 +1,129 @@ +--- +sidebar_label: data +title: data Config +description: Вы можете узнать о конфигурации data в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# data + +### Описание {#description} + +@short: Необязательный. Массив объектов с данными для таблицы Pivot + +### Использование {#usage} + +~~~jsx +data?: []; +~~~ + +### Параметры {#parameters} + +Каждый объект массива `data` представляет собой строку. Значение по умолчанию — пустой массив. +У свойства `data` нет прямых вложенных свойств. Однако каждый объект в массиве может содержать любое количество свойств, которые будут представлять измерения и значения для таблицы Pivot. + +Пример массива `data`: + +~~~jsx +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + { + name: "Argentina", + year: 2017, + continent: "South America", + form: "Republic", + gdp: 212.507, + oil: 1.732, + balance: 7.167, + when: new Date("1/15/2017") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 260.071, + oil: 2.845, + balance: 6.728, + when: new Date("6/16/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 324.405, + oil: 4.333, + balance: 5.99, + when: new Date("2/20/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 305.763, + oil: 2.626, + balance: 7.544, + when: new Date("8/17/2014") + }, + //другие данные +]; +~~~ + +### Пример {#example} + +~~~jsx {3-29} +const table = new pivot.Pivot("#root", { + fields, + data: [ + { + rank: 1, + title: "Shingeki no Kyojin: The Final Season - Kanketsu-hen", + popularity: 609, + genre: "Action", + studio: "MAPPA", + type: "Special", + episodes: 2, + duration: 61, + members: 347875, + score: 9.17, + }, + { + rank: 2, + title: "Fullmetal Alchemist: Brotherhood", + popularity: 3, + genre: "Action", + studio: "Bones", + type: "TV", + episodes: 64, + duration: 24, + members: 3109951, + score: 9.11 + }, + //другие объекты данных + ], + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/fields-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/fields-property.md new file mode 100644 index 0000000..5a5118a --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/fields-property.md @@ -0,0 +1,112 @@ +--- +sidebar_label: fields +title: fields Config +description: Вы можете узнать о конфиге fields в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# fields + +### Описание {#description} + +@short: Необязательный. Массив объектов с полями для таблицы Pivot + +Свойство `fields` в объекте конфигурации управляет тем, как виджет интерпретирует типы полей данных, которые он получает, и позволяет задать порядок сортировки для поля. + +### Использование {#usage} + +~~~jsx +fields?: [{ + id: string, + label?: string, + type: "number" | "date" | "text", + sort?: "asc" | "desc" | ((a: any, b: any) => number), + format?: string | boolean | numberFormatOptions{} +}]; +~~~ + +### Параметры {#parameters} + +По умолчанию, если свойство не задано, виджет автоматически анализирует входящие данные и заполняет объект `fields` соответствующим образом. + +Каждый объект в массиве `fields` должен содержать следующие свойства: + +- `id` - (обязательный) идентификатор поля +- `label` - (необязательный) метка поля, отображаемая в интерфейсе +- `type` - (обязательный) тип данных в поле ( "number", "date" или "text") +- `sort` - (необязательный) определяет порядок сортировки по умолчанию для поля. Принимает "asc", "desc" или пользовательскую функцию сортировки +- `format` - (необязательный) позволяет настроить формат чисел и дат в поле; формат также будет применяться при [экспорте](guides/exporting-data.md) + - `string` - (необязательный) формат для дат (по умолчанию Pivot использует `dateFormat` из локали) + - `boolean` - (необязательный) если установлено значение **false**, число отображается как есть, без какого-либо форматирования + - `numberFormatOptions` - (необязательный) объект с параметрами форматирования числовых полей; по умолчанию числа отображаются с максимум 3 знаками после запятой и применяется разделение групп для целой части. + - `minimumIntegerDigits`(number) - (необязательный) минимальное количество целых цифр (например, если значение равно 2, число 1 будет отображено как "01"); по умолчанию 1; + - `minimumFractionDigits`(number) - (необязательный) минимальное количество дробных знаков (например, если значение равно 2, число 10.5 будет отображено как "10.50"); по умолчанию 0; + - `maximumFractionDigits`(number) - (необязательный) максимальное количество дробных знаков (например, если значение равно 2, число 10.3333... будет отображено как "10.33"); по умолчанию 3; + Подробнее о параметрах цифр см. в [Параметры цифр](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumintegerdigits) + - `prefix` (string) - (необязательный) строка (перед числом) для дополнительных символов, например обозначения валюты + - `suffix` (string) - (необязательный) строка (после числа) для дополнительных символов, например обозначения валюты + +:::info +Если шаблон применяется через свойство [`tableShape`](api/config/tableshape-property.md), он переопределит настройки `format`. +::: + +### Пример {#example} + +~~~jsx {2-34} +const table = new pivot.Pivot("#root", { + fields: [ + { + id: "rank", + label: "Rank", + type: "number" + }, + { + id: "title", + label: "Title", + type: "text" + }, + { + id: "genre", + label: "Genre", + type: "text" + }, + { + id: "studio", + label: "Studio", + type: "text" + }, + { + id: "type", + label: "Type", + type: "text" + }, + { + id: "score", + label: "Score", + type: "number" + }, + //другие поля + ], + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +**Связанные статьи**: + +- [Форматирование чисел](guides/localization.md#number-formatting) +- [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields) + +**Связанный пример**: [Pivot 2. Определение форматов полей](https://snippet.dhtmlx.com/77nc4j8v) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/headershape-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/headershape-property.md new file mode 100644 index 0000000..b6c668c --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/headershape-property.md @@ -0,0 +1,83 @@ +--- +sidebar_label: headerShape +title: headerShape Config +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о конфигурации headerShape. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# headerShape + +### Описание {#description} + +@short: Необязательный. Настраивает внешний вид и поведение заголовков в таблице Pivot + +### Использование {#usage} + +~~~jsx +headerShape?: { + collapsible?: boolean, + vertical?: boolean, + template?: (label: string, field: string, subLabel?: string) => string, + cellStyle?: ( + field: string, + value: any, + area: "rows"|"columns"|"values", + method?: string, + isTotal?: boolean) + => string, +}; +~~~ + +### Параметры {#parameters} + +- `collapsible` - (необязательный) если задано значение **true**, группы измерений в таблице становятся сворачиваемыми. По умолчанию установлено значение **false** +- `vertical` - (необязательный) если задано значение **true**, изменяет ориентацию текста во всех заголовках с горизонтальной на вертикальную. Значение по умолчанию — **false** +- `cellStyle` - (необязательный) функция, применяющая пользовательский стиль к ячейке заголовка. Функция возвращает имя CSS-класса и принимает следующие параметры: + - `field` (string) - (обязательный) строка, представляющая имя поля, которому соответствует ячейка. Для заголовка столбца дерева поле равно "" + - `value` (string | number | date) - (обязательный) значение ячейки + - `area` - (обязательный) строка, указывающая область таблицы, в которой находится ячейка ("rows", "columns" или "values") + - `method` (string) - (необязательный) строка, представляющая операцию, выполняемую для поля из области "values" (например, "sum", "count" и т.д.), или имя предиката, заданного для поля из области "columns" + - `isTotal` - (необязательный) определяет, принадлежит ли ячейка итоговому столбцу +- `template` - (необязательный) определяет формат текста в заголовках. По умолчанию для полей, применяемых как строки, отображается значение параметра `label`, а для полей, применяемых как значения, — метка и метод (например, *Oil(count)*). Функция принимает идентификатор поля, метку и метод или идентификатор предиката (если есть) и возвращает обработанное значение. Шаблон по умолчанию выглядит следующим образом: +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +## Пример {#example} + +В примере ниже для полей **values** заголовок будет отображать метку, название метода (subLabel) и переводить результат в нижний регистр (например, *profit (sum)*): + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // пользовательский шаблон для текста заголовка + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // другие значения + ], + }, + fields, +}); +~~~ + +**Связанные примеры**: +- [Pivot 2. Вертикальная ориентация текста в заголовках сетки](https://snippet.dhtmlx.com/4qroi8ka) +- [Pivot 2. Сворачиваемые столбцы](https://snippet.dhtmlx.com/pt2ljmcm) +- [Pivot 2. Добавление пользовательского CSS для ячеек таблицы и заголовков](https://snippet.dhtmlx.com/nfdcs4i2) + +**Связанные статьи**: +- [Конфигурация](guides/configuration.md) +- [Стиль ячеек](guides/stylization.md#cell-style) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/limits-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/limits-property.md new file mode 100644 index 0000000..4a7e996 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/limits-property.md @@ -0,0 +1,61 @@ +--- +sidebar_label: limits +title: limits Config +description: Вы можете узнать о конфиге limits в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# limits + +### Описание {#description} + +@short: Необязательный. Определяет максимальный лимит количества строк и столбцов в итоговом наборе данных + +Смотрите также [Ограничение данных](guides/working-with-data.md#limiting-loaded-data). + +### Использование {#usage} + +~~~jsx +limits?: { + rows?: number, + columns?: number, + raws?: number +}; +~~~ + +### Параметры {#parameters} + +Параметры определяют, когда следует прерывать отрисовку данных: + +- `rows` - (необязательный) задаёт максимальное количество строк в итоговом наборе данных; значение по умолчанию — 10000. +- `columns` - (необязательный) задаёт максимальное количество столбцов в итоговом наборе данных; значение по умолчанию — 5000. +- `raws` - (необязательный) максимальное количество строк исходных данных до их группировки (необработанные записи, используемые для агрегации); значение по умолчанию — бесконечность. + +:::note +Лимиты применяются для больших наборов данных. Значения лимитов являются приблизительными и не отражают точное количество строк и столбцов. +::: + +## Пример {#example} + +~~~jsx {18} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + ], + }, + limits:{ rows: 25, columns: 4 } +}); +~~~ + +**Связанный пример**: [Pivot 2. Ограничения данных](https://snippet.dhtmlx.com/7ryns8oe) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/locale-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/locale-property.md new file mode 100644 index 0000000..658f15d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/locale-property.md @@ -0,0 +1,51 @@ +--- +sidebar_label: locale +title: locale Config +description: Вы можете узнать о конфиге locale в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, изучайте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# locale + +### Описание {#description} + +@short: Необязательный. Объект пользовательской локали Pivot + +### Использование {#usage} + +~~~jsx +locale?: object; +~~~ + +### Конфигурация по умолчанию {#default-config} + +По умолчанию Pivot использует локаль [английского](guides/localization.md#default-locale) языка. Вы также можете задать пользовательскую локаль. + +:::tip +Чтобы изменить текущую локаль динамически, используйте метод [`setLocale()`](api/methods/setlocale-method.md) компонента Pivot +::: + +### Пример {#example} + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + + locale: pivot.locales.cn, // локаль "cn" будет установлена изначально + // другие параметры +}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/methods-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/methods-property.md new file mode 100644 index 0000000..db8e22d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/methods-property.md @@ -0,0 +1,163 @@ +--- +sidebar_label: methods +title: methods Config +description: Вы можете узнать о конфигурационном параметре methods в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# methods + +### Описание {#description} + +@short: Необязательный. Задаёт пользовательские математические методы для агрегации данных + +### Использование {#usage} + +~~~jsx +methods?: { + [method: string]: { + type?: 'number' | 'date' | 'text' | [], + label?: string, + handler?: (values: number[]) => number, + branchMode?: "raw"|"result", + branchMath?: string + } +}; +~~~ + +### Параметры {#parameters} + +Каждый метод представлен парой «ключ-значение», где `method` — это имя метода, а значение — объект, описывающий поведение метода. Каждый объект имеет следующие параметры: + +- `handler` - (обязателен для пользовательских методов) функция, которая вычисляет агрегированное значение из массива чисел; функция принимает массив значений на вход и возвращает одно значение на выходе +- `type` - (необязательный) тип данных, для которого подходит данный метод; может быть "number", "date" или "text" или массивом этих значений +- `label` - (необязательный) метка метода, отображаемая в интерфейсе +- `branchMode` - (необязательный) определяет режим вычисления итоговых значений для древовидной таблицы; `branchMode` может быть задан как `raw` для вычисления на основе всех исходных данных; `result` (по умолчанию) задаётся для вычисления на основе уже обработанных данных в режиме дерева +- `branchMath` - (необязательный) имя метода для вычисления итоговых значений в режиме дерева; по умолчанию совпадает с именем метода (для метода "max" параметр `branchMath` также равен "max") + +По умолчанию свойство `methods` является пустым объектом {}, что означает отсутствие пользовательских методов. Количество вложенных свойств, которые можно определить в объекте methods, не ограничено. + +Предопределённые методы: + +~~~jsx +defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +Определение каждого метода можно посмотреть здесь: [Применение методов](guides/working-with-data.md#default-methods) + +## Пример {#example} + +В приведённом ниже примере показано, как вычислить количество уникальных и средних значений для типа date. Функция **countUnique** принимает массив чисел (значений) на вход и вычисляет точное количество уникальных значений с помощью метода **reduce**. Вложенное свойство **countunique_date** содержит обработчик с функцией, которая получает уникальные значения из массива дат. Вложенное свойство **average_date** содержит обработчик, который вычисляет средние значения из массива дат. + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique" + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// показывать целые числа для результатов "count" и "unique count" +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// строку даты в Date +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +**Связанный пример**: [Pivot 2. Пользовательские математические методы](https://snippet.dhtmlx.com/lv90d8q2) + +**Связанная статья**: [Применение математических методов](guides/working-with-data.md#applying-maths-methods) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/predicates-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/predicates-property.md new file mode 100644 index 0000000..cdc5308 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/predicates-property.md @@ -0,0 +1,117 @@ +--- +sidebar_label: predicates +title: predicates Config +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о конфиге predicates. Изучайте руководства разработчика и справочник API, просматривайте примеры кода и живые демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# predicates + +### Описание {#description} + +@short: Необязательный. Предоставляет пользовательские функции предварительной обработки для измерений данных (строки, столбцы) + +Определяет, как данные должны быть изменены перед применением. + +### Использование {#usage} + +~~~jsx +predicates?: { + [key: string]: { + handler: (value: any) => any, + type: 'number' | 'date' | 'text' | [], + label?: string | (type: 'number' | 'date' | 'text') => string, + template?: (value: any, locale?: any) => string, + field?: (value:string) => boolean, + filter?: { + type: "number"|"text"|"date"|"tuple", + format?:(any) => string + } + } +}; +~~~ + +### Параметры {#parameters} + +Свойство является объектом, где ключ — это имя пользовательской функции, а значение — объект с определениями самих функций. Объект предиката может содержать несколько пар ключ-функция, и все они будут доступны для использования в конфигурации Pivot. Каждый объект имеет следующие параметры: + +- `label` - (необязательный) метка предиката, отображаемая в GUI в выпадающем списке среди опций модификаторов данных для строки/столбца +- `type` - (обязательный) определяет, для каких типов полей можно применять данный предикат; допустимые значения: "number", "date", "text" или массив этих значений +- `field` - (необязательный) функция, определяющая порядок обработки данных для указанного поля; принимает идентификатор поля в качестве параметра и возвращает **true**, если предикат должен быть добавлен к указанному полю +- `filter` - (необязательный) по умолчанию тип фильтра берётся из параметра `type`, но если требуется другой, можно использовать этот объект `filter`. Он имеет следующие параметры: + - `type` - (необязательный) определяет, какой тип поля будет применён: "number"|"text"|"date"|"tuple". "tuple" — это комбинированный фильтр для числовых значений (данные фильтруются по числовому значению, но в фильтре отображается текстовое значение) + - `format` - (необязательный) функция, определяющая формат отображения вариантов фильтрации; если формат не задан, применяется формат из параметра `template`; если `type` (для объекта `filter`) не указан, формат будет применён для типа, заданного в параметре `type` предиката +- `handler` - (обязательный для пользовательских предикатов) функция, определяющая порядок обработки данных; функция принимает единственный аргумент — обрабатываемое значение — и возвращает обработанное значение +- `template` - (необязательный) функция, определяющая способ отображения данных; функция возвращает обработанное значение, принимает значение, возвращённое `handler`, и при необходимости позволяет локализовать текстовые значения с помощью [`locale`](api/config/locale-property.md) + +Следующие предикаты применяются по умолчанию, если через свойство `predicates` не задан ни один предикат: + +~~~jsx +const defaultPredicates = { + // служебный предикат, представляющий исходное (необработанное) значение + $empty: { label: (type) => `Raw ${type}`, type: ["number", "date", "text"] }, + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +## Пример {#example} + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// строку с датой в объект Date +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +**Связанная статья**: [Обработка данных с помощью предикатов](guides/working-with-data.md#processing-data-with-predicates) + +**Связанный пример**: [Pivot 2. Пользовательские предикаты](https://snippet.dhtmlx.com/mhymus00) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/readonly-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/readonly-property.md new file mode 100644 index 0000000..a3bd0e8 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/readonly-property.md @@ -0,0 +1,52 @@ +--- +sidebar_label: readonly +title: readonly Config +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о конфигурационном параметре readonly. Изучайте руководства разработчика и справочник API, запускайте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# readonly + +### Описание {#description} + +@short: Необязательный. Включает/отключает режим только для чтения + +В режиме только для чтения настройка структуры Pivot через интерфейс недоступна. + +### Использование {#usage} + +~~~jsx + readonly?: boolean; +~~~ + +### Параметры {#parameters} + +Свойство может принимать значения **true** или **false**: + +- `true` — включает режим только для чтения +- `false` — значение по умолчанию, отключает режим только для чтения + +## Пример {#example} + +~~~jsx {18} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + readonly: true +}); +~~~ + +**Связанный пример**: [Pivot 2. Режим только для чтения](https://snippet.dhtmlx.com/0k0mvycv) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md new file mode 100644 index 0000000..ae233f2 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md @@ -0,0 +1,131 @@ +--- +sidebar_label: tableShape +title: Конфигурация tableShape +description: Вы можете узнать о конфигурации tableShape в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства разработчика и справочник API, ознакомьтесь с примерами кода и живыми демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# tableShape + +### Описание {#description} + +@short: Необязательный. Настраивает внешний вид таблицы Pivot + +### Использование {#usage} + +~~~jsx +tableShape?: { + templates?: { + [field: string]: ( + value: any, + operation: string + ) => any; + }, + totalRow?: boolean | "sumOnly", + totalColumn?: boolean | "sumOnly", + marks?: { + [cssClass: string]: ((v: any, columnData: any, rowData: any) => boolean) + | "max" + | "min" + }, + sizes?: { + rowHeight?: number, + headerHeight?: number, + columnWidth?: number, + footerHeight?: number + }, + tree?:boolean, + cleanRows?: boolean, + split?: { + left?: boolean, + right?: boolean, + }, + cellStyle?: ( + field: string, + value: any, + area: "rows"|"columns"|"values", + method?: string, + isTotal?: "row"|"column"|"both") + => string, +}; +~~~ + +### Параметры {#parameters} + +- `templates` - (необязательный) позволяет задавать шаблоны для ячеек; это объект, где: + - каждый ключ — это идентификатор поля + - значение — функция, которая возвращает строку и принимает значение ячейки и операцию. Ко всем столбцам, основанным на указанном поле, будет применён соответствующий шаблон. Например, это позволяет задавать единицы измерения или возвращать необходимое количество знаков после запятой для числовых значений и т. д. Смотрите пример ниже. +- `marks` - (необязательный) позволяет отмечать ячейку с необходимыми значениями. Это объект, где ключи — имена CSS-классов, а значения — либо функция, либо одна из предопределённых строк ("max", "min"). Функция должна возвращать булево значение для проверяемого значения. Если возвращается **true**, CSS-класс присваивается ячейке. Подробнее с примерами смотрите здесь: [Стилизация ячеек](guides/stylization.md#cell-style). +- `sizes` - (необязательный) определяет следующие параметры размеров таблицы: + - `rowHeight` - (необязательный) высота строки в таблице Pivot в пикселях. Значение по умолчанию — 34 + - `headerHeight` - (необязательный) высота заголовка в пикселях; значение по умолчанию — 30 + - `footerHeight` - (необязательный) высота подвала в пикселях; значение по умолчанию — 30 + - `columnWidth` - (необязательный) ширина столбца в пикселях; значение по умолчанию — 150 +- `cellStyle` - (необязательный) функция, применяющая пользовательский стиль к ячейке. Функция принимает следующие параметры: + - `field` - (обязательный) строка, представляющая имя поля, к которому применяется стиль + - `value` - (обязательный) значение ячейки (фактические данные для данной строки и столбца) + - `area` - (обязательный) строка, указывающая область таблицы, в которой находится ячейка ("rows", "columns" или "values") + - `method` - (необязательный) строка, представляющая операцию, выполняемую над ячейкой (например, "sum", "count" и т. д.) + - `isTotal` - (необязательный) определяет, принадлежит ли ячейка итоговой строке, итоговому столбцу или и тому, и другому: "row"|"column"|"both" + Функция `cellStyle` возвращает строку, которая может использоваться как имя CSS-класса для применения определённых стилей к ячейке. +- `tree` - (необязательный) если установлено значение **true**, включает режим дерева, при котором данные отображаются с раскрываемыми строками; значение по умолчанию — **false**. Подробнее с примерами смотрите здесь: [Переключение в режим дерева](guides/configuration.md#enabling-the-tree-mode) +- `totalColumn` - (необязательный) если **true**, включает генерацию итогового столбца с итоговыми значениями для строк (по умолчанию установлено **false**). Если установлено значение "sumOnly", будет сгенерирован столбец с итоговой суммой (доступно только для операции sum) +- `totalRow` - (необязательный) если **true**, включает генерацию подвала с итоговыми значениями (по умолчанию установлено **false**). Если установлено значение "sumOnly", будет сгенерирована строка с итоговым значением (доступно только для операции sum) +- `cleanRows` - (необязательный) если установлено значение **true**, дублирующиеся значения в масштабных столбцах скрываются в табличном представлении. Значение по умолчанию — **false** +- `split` - (необязательный) позволяет закреплять столбцы справа или слева в зависимости от указанного параметра (смотрите [Закрепление столбцов](guides/configuration.md#freezing-columns)): + - `left` (boolean) - если установлено значение **true** (по умолчанию **false**), фиксирует столбцы слева, делая их статичными и видимыми при прокрутке. Количество закреплённых столбцов равно числу полей строк, определённых в свойстве [`config`](api/config/config-property.md) + - `right` (boolean) - фиксирует итоговые столбцы справа; значение по умолчанию — **false** + +По умолчанию `tableShape` не определён, что означает отсутствие итоговой строки и итогового столбца, отсутствие применённых шаблонов и маркировок, данные отображаются в виде таблицы, а не дерева, и столбцы не фиксируются при прокрутке. + +## Пример {#example} + +В приведённом ниже примере мы применяем шаблон к ячейкам *state*, чтобы отображать составное название штата (полное название и аббревиатуру). + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", +// другие значения, +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // задаём шаблон для настройки значений ячеек "state" + state: v => v+ ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // другие значения + ], + }, + fields, +}); +~~~ + +**Связанные примеры**: + +- [Pivot 2. Режим дерева](https://snippet.dhtmlx.com/6ylkoukn) +- [Pivot 2. Замороженные (фиксированные) столбцы](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. Задать высоту строки, заголовка, подвала и ширину всех столбцов](https://snippet.dhtmlx.com/x46uyfy9) +- [Pivot 2. Чистые строки](https://snippet.dhtmlx.com/rwwhgv2w?tag=pivot) +- [Pivot 2. Добавление пользовательского CSS для ячеек таблицы и заголовка](https://snippet.dhtmlx.com/nfdcs4i2) + +**Связанные статьи**: +- [Конфигурация](guides/configuration.md) +- [Стиль ячеек](guides/stylization.md#cell-style) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/add-field-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/add-field-event.md new file mode 100644 index 0000000..501f8a2 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/add-field-event.md @@ -0,0 +1,74 @@ +--- +sidebar_label: add-field +title: Событие add-field +description: Вы можете узнать о событии add-field в документации библиотеки DHTMLX JavaScript Pivot. Ознакомьтесь с руководствами разработчика и справочником API, изучите примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# add-field + +### Описание {#description} + +@short: Срабатывает, когда новое поле добавляется в область строк, столбцов или значений + +### Использование {#usage} + +~~~jsx +"add-field": ({ + id?: string | number, + area: string, + field: string | number, + method?: string +}) => boolean; +~~~ + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующими параметрами: + +- `id` - (необязательный) желаемый идентификатор нового поля; если не задан, добавляется автоматически сгенерированный id +- `area` - (обязательный) название области, в которую добавляется новое поле: "rows", "columns" или "values" +- `field` - (обязательный) название поля +- `method` - (необязательный) определяет метод агрегации данных (если не указан, устанавливается первый метод, подходящий для данного типа данных); метод может быть одним из следующих: + - для области **values** является обязательным — это строка с одним из типов операций над данными: [Методы по умолчанию](guides/working-with-data.md#default-methods) + - для областей **rows** и **columns** является необязательным; если значение задано, это предикат — пользовательский или один из встроенных: "year", "quarter", "month", "week", "day", "hour", "minute". По умолчанию используется исходное значение. + Если задан пользовательский предикат или метод, необходимо указать id для свойства [predicates](api/config/predicates-property.md) или [methods](api/config/methods-property.md). + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Пример {#example} + +В приведённом ниже примере используется метод [`api.intercept()`](api/internal/intercept-method.md) для добавления нового метода к полю значений с типом данных **number**: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//добавление значений с заранее заданным методом +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "min"; + } +}); +~~~ + +**Связанные статьи**: [api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md new file mode 100644 index 0000000..e66a8b0 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: apply-filter +title: apply-filter Event +description: Вы можете узнать о событии apply-filter в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную пробную версию DHTMLX Pivot. +--- + +# apply-filter + +### Описание {#description} + +@short: Срабатывает при применении фильтра + +### Использование {#usage} + +~~~jsx +"apply-filter": ({ + rule: {} +}) => boolean | void; +~~~ + +### Параметры {#parameters} + +Калбэк действия принимает объект со следующими параметрами: + +- `rule` - любой объект конфигурации фильтра со следующими параметрами: + - `field` - (обязательный) идентификатор поля, к которому будет применён фильтр + - `filter` - (обязательный) тип фильтра: + - для текстовых значений: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith + - для числовых значений: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains + - для типов дат: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween + - `value` - (необязательный) значение для фильтрации + - `includes` - (необязательный) массив значений для отображения из тех, что уже отфильтрованы; доступно для текстовых и датовых значений + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Пример {#example} + +~~~jsx {20-23} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//вывод в консоль метки поля, к которому был применён фильтр +table.api.on("apply-filter", (ev) => { + console.log("The field to which filter was applied:", ev.rule.field); +}); +~~~ + +**Связанные статьи**: [api.on()](api/internal/on-method.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md new file mode 100644 index 0000000..e0d1191 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md @@ -0,0 +1,82 @@ +--- +sidebar_label: delete-field +title: delete-field Event +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о событии delete-field. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# delete-field + +### Описание {#description} + +@short: Срабатывает при удалении поля + +### Использование {#usage} + +~~~jsx +"delete-field": ({ + area: string, + id: string | number +}) => boolean | void; +~~~ + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующими параметрами: + +- `area` - (обязательный) название области, из которой удаляется поле; может быть областью "rows", "columns" или "values" +- `id` - (обязательный) идентификатор удаляемого поля + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Пример {#example} + +В примере ниже действие `delete-field` вызывается через метод [`api.exec()`](api/internal/exec-method.md). Последнее поле удаляется из области **values**. Метод [`api.getState()`](api/internal/getstate-method.md) здесь используется для получения текущего состояния [`config`](api/config/config-property.md) Pivot. Действие будет вызвано по нажатию кнопки. + +~~~jsx {31-34} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//вызов методов API: удаление определённого значения из values в config +function removeLastField() { + if (table.api) { + const state = table.api.getState(); + const config = state.config; + + const count = config.values.length; + + if (count) { + const lastValue = config.values[count - 1]; + + table.api.exec("delete-field", { + area: "values", + id: lastValue.id, // автоматически сгенерированный ID элемента, добавленного в config.values + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/move-field-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/move-field-event.md new file mode 100644 index 0000000..09adc88 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/move-field-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: move-field +title: move-field Event +description: Документация по событию move-field в библиотеке DHTMLX JavaScript Pivot. Руководства разработчика и справочник по API, примеры кода и живые демо, а также бесплатная 30-дневная ознакомительная версия DHTMLX Pivot. +--- + +# move-field + +### Описание {#description} + +@short: Срабатывает при изменении порядка полей + +### Использование {#usage} + +~~~jsx +"move-field": ({ + area: string, + id: string | number, + before?: string, + after?: string +}) => void | boolean; +~~~ + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующими параметрами: + +- `area` - (обязательный) название области, в которой выполняется изменение порядка: "rows", "columns" или "values" +- `id` - (обязательный) идентификатор перемещаемого поля +- `before` - (необязательный) идентификатор поля, перед которым размещается перемещаемое поле +- `after` - (необязательный) идентификатор поля, после которого размещается перемещаемое поле + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Пример {#example} + +~~~jsx {20-23} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//вывести в консоль идентификатор поля, порядок которого изменился +table.api.on("move-field", (ev) => { + console.log("The id of the reordered field:", ev.id); +}); +~~~ + +**Связанные статьи**: [api.on()](api/internal/on-method.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md new file mode 100644 index 0000000..659aae8 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md @@ -0,0 +1,95 @@ +--- +sidebar_label: open-filter +title: open-filter Событие +description: Вы можете узнать о событии open-filter в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства разработчика и справочник API, ознакомьтесь с примерами кода и живыми демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# open-filter + +### Описание {#description} + +@short: Срабатывает при активации фильтра для поля + +### Использование {#usage} + +~~~jsx +"open-filter": ({ + id: string | null, + area?: "values" | "rows" | "columns" +}) => boolean | void; +~~~ + +### Параметры {#parameters} + +Калбэк действия принимает следующие параметры: + +- `area` - область, в которой применяется поле ("rows", "columns", "values") +- `id` - идентификатор поля; если передан единственный аргумент `id` со значением null, фильтр будет закрыт. + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Возвращает {#returns} + +Функция может возвращать булево значение или void. При возврате **false** соответствующая операция события будет прервана. + +### Пример {#example} + +Пример ниже показывает, как скрыть панель конфигурации при закрытии блока фильтра: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + if(!ev.id) { + table.api.exec("show-config-panel", { + mode: false + }); + } +}); +~~~ + +В следующем примере идентификатор поля, для которого активирован фильтр, выводится в консоль: + +~~~jsx {20-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + console.log("The field id for which filter is activated:", ev.id); +}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/render-table-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/render-table-event.md new file mode 100644 index 0000000..085f580 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/render-table-event.md @@ -0,0 +1,178 @@ +--- +sidebar_label: render-table +title: render-table Event +description: Вы можете узнать о событии render-table в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# render-table + +### Описание {#description} + +@short: Срабатывает после обработки конфигурации виджета и непосредственно перед рендерингом таблицы + +Позволяет изменить итоговую конфигурацию таблицы на лету или полностью предотвратить её рендеринг. + +### Использование {#usage} + +~~~jsx +"render-table": ({ + config: { + columns?: any[], + data?: any[], + footer?: boolean, + sizes?: { + rowHeight?: number, + headerHeight?: number, + columnWidth?: number, + footerHeight?: number + }, + split?: { + left?: number; + right?: number; + }, + tree?: boolean, + cellStyle?: (row: any, col: any) => string, + } +}) => boolean | void; +~~~ + +### Параметры {#parameters} + +Калбэк события принимает объект `config` со следующими параметрами: + +- `columns` - (опционально) массив столбцов, где каждый объект содержит следующие параметры: + - `id` (number) - (обязательно) идентификатор столбца + - `cell` (any) - (опционально) шаблон с содержимым ячейки (см. [Добавление шаблонов через хелпер template](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (опционально) шаблон, определённый через свойство [`tableShape`](api/config/tableshape-property.md) + - `fields` (array) - (опционально) определяет поля в иерархическом столбце в режиме дерева. Отражает поля, отображаемые в данном столбце на разных уровнях + - `field` - (опционально) строка, являющаяся идентификатором поля + - `method` (string) - (опционально) метод, если он задан для поля в данном столбце + - `methods` (array) - (опционально) определяет методы, применяемые к полям в иерархическом столбце в режиме дерева + - `format` (string or object) - (обязательно) формат даты или числа (см. [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields)) + - `isNumeric` (boolean) - (опционально) определяет, содержит ли столбец числовые значения + - `isTotal` (boolean) - (опционально) определяет, является ли столбец итоговым + - `area` (string) - (опционально) область, в которой отображается столбец: "rows", "columns", "values" + - `header` - (опционально) массив ячеек заголовка со следующими свойствами для каждой ячейки: + - `text` (string) - (опционально) текст ячейки, форматированное значение или значение, обработанное шаблоном предиката + - `rowspan` (number) - (опционально) количество строк, которые должен охватывать заголовок + - `colspan` (number) - (опционально) количество столбцов, которые должен охватывать заголовок + - `value` (any) - (обязательно) исходное значение, если ячейка принадлежит области "columns" + - `field` (string) - (обязательно) поле, значение которого отображается, если ячейка принадлежит области "columns" + - `method` (string) - (обязательно) предикат поля, если ячейка принадлежит области "columns" и предикат задан + - `format` (string or object) - формат даты или числа (см. [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields)) + - `footer` - (опционально) метка заголовка или объект с настройками футера, аналогичными настройкам заголовка + - `data` - (опционально) массив объектов с данными для таблицы; каждый объект представляет строку: + - `id` (number) - (обязательно) идентификатор строки + - `values` (array) - (обязательно) массив с данными строки + - `open` (boolean) - (опционально) состояние ветки + - `$level` (boolean) - (опционально) индекс ветки +- `footer` - (опционально) если установлено значение **true**, футер таблицы отображается внизу таблицы; по умолчанию установлено значение **false** и футер не виден +- `sizes` - (опционально) объект с настройками размеров таблицы: columnWidth, footerHeight, headerHeight, rowHeight +- `split` (object) - (опционально) объект со следующими свойствами: + - `left` (number) - количество фиксированных столбцов слева + - `right` (number) - количество фиксированных столбцов справа +- `tree` - (опционально) определяет, включён ли режим дерева (**true**, если включён) +- `cellStyle` - (опционально) функция, применяющая пользовательский стиль к ячейке. Принимает объекты строки и столбца и возвращает строку с именем CSS-класса: `(row, col) => string` + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Возвращаемое значение {#returns} + +Калбэк может возвращать boolean или void. +Если обработчик события возвращает **false**, операция будет заблокирована. В данном случае это предотвратит рендеринг таблицы. + +### Пример {#example} + +Следующий пример показывает, как вывести объект [`config`](api/config/config-property.md) в консоль и добавить футер. + +~~~jsx {20-28} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.intercept("render-table", (ev) => { + console.log(ev.config); //вывести объект config + console.log(ev.config.columns); //вывести массив columns + + ev.config.footer = true; + ev.config.columns[0].footer = ["Custom footer"]; + + // возврат "false" здесь предотвратит рендеринг таблицы +}); +~~~ + +Следующий пример показывает, как раскрывать/сворачивать все строки по нажатию кнопки. Режим дерева должен быть включён через свойство [`tableShape`](api/config/tableshape-property.md). + +~~~jsx +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true, + }, + fields, + data: dataset, + config: { + rows: ["type", "studio"], + columns: [], + values: [ + { + field: "score", + method: "max" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + }, + { + field: "episodes", + method: "count" + } + ] + } +}); + +const api = table.api; +const tableApi = api.getTable(); + +// закрываем все ветки таблицы при обновлении конфигурации таблицы +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // возврат "false" здесь предотвратит рендеринг таблицы + // return false; +}); + +function openAll() { + tableApi.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableApi.exec("close-row", { id: 0, nested: true }); +} +~~~ + +Смотрите также, как настроить функцию разделения с помощью события `render-table`: [Фиксация столбцов](guides/configuration.md#freezing-columns). + +**Связанная статья**: [Хелпер pivot.template](api/helpers/template.md) + +**Связанный пример**: [Pivot 2. Пользовательские фиксированные столбцы (ваше число)](https://snippet.dhtmlx.com/53erlmgp) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md new file mode 100644 index 0000000..e2e1d34 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md @@ -0,0 +1,60 @@ +--- +sidebar_label: show-config-panel +title: Событие show-config-panel +description: Вы можете узнать о событии show-config-panel в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# show-config-panel + +### Описание {#description} + +@short: Срабатывает при изменении видимости панели конфигурации + +### Использование {#usage} + +~~~jsx +"show-config-panel": ({ + mode: boolean +}) +~~~ + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующим параметром: + +- `mode` - (обязательный) если значение установлено в **true** (по умолчанию), панель конфигурации отображается; если в **false** — панель конфигурации скрыта + +:::info +Для обработки внутренних событий вы можете использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Пример {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//скрыть панель конфигурации +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +**Связанные статьи**: +- [метод `showConfigPanel()`](api/methods/showconfigpanel-method.md) +- [свойство `configPanel`](api/config/configpanel-property.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/update-config-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/update-config-event.md new file mode 100644 index 0000000..a21b5e1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/update-config-event.md @@ -0,0 +1,78 @@ +--- +sidebar_label: update-config +title: update-config Event +description: Вы можете узнать о событии update-config в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства разработчика и справочник API, ознакомьтесь с примерами кода и живыми демо, загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# update-config + +### Описание {#description} + +@short: Срабатывает при изменении строк, столбцов или функций агрегации через интерфейс Pivot + +Это действие удобно для сохранения пользовательской конфигурации агрегации, чтобы её можно было применить при следующем использовании виджета — позволяя пользователю продолжить с того места, где он остановился. + +### Использование {#usage} + +~~~jsx +"update-config": ({ + rows: string[], + columns: string[], + values: [], + filters: {} +}) => boolean | void; +~~~ + +### Параметры {#parameters} + +Колбэк события принимает объект с обработанными параметрами [`config`](api/config/config-property.md): + +- `rows` - строки таблицы Pivot. Объект с идентификатором поля и методом извлечения данных; параметры объекта: + - `field` - идентификатор поля + - `method` - метод извлечения данных (для полей с данными на основе времени) +- `columns` - определяет столбцы таблицы Pivot. Объект с идентификатором поля и методом извлечения данных; параметры объекта: + - `field` - идентификатор поля + - `method` - определяет метод извлечения данных (для полей с данными на основе времени). + По умолчанию методы доступны для полей на основе времени (тип **date**) со следующими значениями: "year", "quarter", "month", "week", "day", "hour", "minute" +- `values` - определяет агрегацию данных для ячеек таблицы Pivot. Объект, содержащий идентификатор поля и метод агрегации данных. Параметры объекта: + - `field` - идентификатор поля + - `method` - определяет метод извлечения данных; о методах и доступных вариантах см. [Применение методов](guides/working-with-data.md#default-methods) +- `filters` - (необязательный) определяет способ фильтрации данных в таблице; объект с идентификаторами полей и методом агрегации данных. Описание объекта `filter` смотрите здесь: [`config`](api/config/config-property.md) + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Возвращает {#returns} + +Колбэк может возвращать boolean или void. +Если функция-обработчик события возвращает *false*, операция, вызвавшая событие, блокируется и выполнение `update-config` прерывается. + +### Пример {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//вывести объект config в консоль +table.api.on("update-config", (config) => { + console.log("Config has changed", config); +}); +~~~ + +**Связанные статьи**: [api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/events/update-field-event.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/update-field-event.md new file mode 100644 index 0000000..304cee9 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/events/update-field-event.md @@ -0,0 +1,67 @@ +--- +sidebar_label: update-field +title: update-field Event +description: Вы можете узнать о событии update-field в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, просматривайте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# update-field + +### Описание {#description} + +@short: Срабатывает при обновлении поля + +### Использование {#usage} + +~~~jsx +"update-field": ({ + id: string | number, + method: string, + area: string +}) => boolean; +~~~ + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующими параметрами: + +- `id` - (обязательный) идентификатор обновляемого поля +- `method` - (обязательный) метод может принимать одно из следующих значений: + - для области **values** — строка с одним из типов операций над данными: [Методы по умолчанию](guides/working-with-data.md#default-methods) + - для областей **rows** и **columns** — значение предиката данных, которое может быть одним из следующих: "year", "quarter", "month", "week", "day", "hour", "minute". По умолчанию устанавливается исходное значение. + Если задан пользовательский предикат или метод, идентификатор должен быть указан для свойства [predicate](api/config/predicates-property.md) или [methods](api/config/methods-property.md). +- `area` - (обязательный) название области, в которой обновляется поле: "rows", "columns" или "values" + +:::info +Для обработки внутренних событий можно использовать [методы Event Bus](api/overview/internal-eventbus-overview.md) +::: + +### Пример {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//вывести id обновлённого поля в консоль +table.api.on("update-field", (ev) => { + console.log("The id of the field that was updated:", ev.id); +}); +~~~ + +**Связанные статьи**: +- [api.on()](api/internal/on-method.md) +- [methods](api/config/methods-property.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/helpers/template.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/helpers/template.md new file mode 100644 index 0000000..8595fbc --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/helpers/template.md @@ -0,0 +1,89 @@ +--- +sidebar_label: template +title: template +description: В документации по библиотеке DHTMLX JavaScript Pivot вы можете узнать о хелпере template. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +### Описание {#description} + +Функция `template` позволяет применять шаблон к ячейкам заголовка и тела таблицы. + +### Использование {#usage} + +Для ячеек тела: + +~~~jsx +pivot.template({value, method, row, column}) => string; +~~~ + +Для ячеек заголовка: + +~~~jsx +pivot.template({value, field, method, cell, column}) => string; +~~~ + +### Параметры {#parameters} + +Для ячеек тела функция принимает следующие параметры: + +- `value` (any) - (обязательный) необработанное значение ячейки +- `method` (string) - (обязательный) метод или предикат, используемый для столбца +- `row` - (обязательный) объект с данными строки: + - `id` (number) - (обязательный) идентификатор строки + - `values` (array) - (обязательный) массив с данными строки + - `open` (boolean)- (необязательный) состояние ветки + - `$level` (boolean)- (необязательный) индекс ветки +- `column` - (обязательный) объект с данными столбца: + - `id` (number) - (обязательный) идентификатор столбца + - `cell` (any) - (необязательный) шаблон с содержимым ячейки (см. [Добавление шаблонов через хелпер template](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (необязательный) шаблон, определённый через свойство [`tableShape`](api/config/tableshape-property.md) + - `fields` (array) - (необязательный) определяет поля в иерархическом столбце в режиме дерева. Отражает поля, отображаемые в этом столбце на разных уровнях + - `field` - (необязательный) строка, являющаяся идентификатором поля + - `method` (string) - (необязательный) метод, если он определён для поля в данном столбце + - `methods` (array) - (необязательный) определяет методы, применяемые к полям в иерархическом столбце в режиме дерева + - `format` (string or object) - (обязательный) формат даты или числовой формат (см. [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields)) + - `isNumeric` (boolean) - (необязательный) определяет, содержит ли столбец числовые значения + - `isTotal` (boolean) - (необязательный) определяет, является ли столбец итоговым + - `area` (string) - (необязательный) область, в которой отрисовывается столбец: "rows", "columns", "values" + - `header`- (необязательный) массив ячеек заголовка со следующими свойствами для каждой ячейки: + - `text` (string) - (необязательный) текст ячейки, отформатированное значение или значение, обработанное шаблоном предиката + - `rowspan` (number) - (необязательный) количество строк, которые должен охватывать заголовок + - `colspan` (number) - (необязательный) количество столбцов, которые должен охватывать заголовок + - `value` (any) - (обязательный) необработанное значение, если ячейка принадлежит области "columns" + - `field` (string) - (обязательный) поле, значение которого отображается, если ячейка принадлежит области "columns" + - `method` (string) - (обязательный) предикат поля, если ячейка принадлежит области "columns" и предикат определён + - `format` (string or object) - формат даты или числовой формат (см. [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields)) + +Для ячеек заголовка параметры функции следующие: + +- `value` (any) - (обязательный) необработанное значение ячейки +- `method` (string) - (необязательный) предикат, используемый для столбца +- `field` (string) - (необязательный) поле, значение которого отображается в ячейке +- `cell` - (обязательный) объект с данными ячейки: + - `text` (string) - (необязательный) текст ячейки, отформатированное значение или значение, обработанное шаблоном предиката + - `rowspan` (number) - (необязательный) количество строк, которые должен охватывать заголовок + - `colspan` (number) - (необязательный) количество столбцов, которые должен охватывать заголовок + - `value` (any) - (обязательный) необработанное значение, если ячейка принадлежит области "columns" + - `field` (string) - (обязательный) поле, значение которого отображается, если ячейка принадлежит области "columns" + - `method` (string) - (обязательный) предикат поля, если ячейка принадлежит области "columns" и предикат определён + - `format` (string or object) - (обязательный) формат даты или числовой формат (см. [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields)) +- `column` - (обязательный) объект с данными столбца (аналогичен объекту для ячейки тела) + +### Пример {#example} + +Фрагмент ниже показывает, как определять шаблоны с помощью хелпера `pivot.template`. Хелпер применяется непосредственно перед отрисовкой таблицы — путём перехвата события [render-table](api/events/render-table-event.md) с помощью метода [api.intercept()](api/internal/intercept-method.md). + +Фрагмент демонстрирует, как добавлять иконки к: + +- ячейкам тела на основе их поля (id, user_score) (шаблон добавляет иконки флага и звезды) +- подписям заголовков на основе имени поля (например, если поле — "id", рядом со значением заголовка добавляется иконка глобуса) +- заголовкам столбцов на основе значения (добавляются цветные индикаторы-стрелки) + + + + +**Связанные статьи**: + +- [`render-table`](api/events/render-table-event.md) +- [Применение шаблонов к ячейкам](guides/configuration.md#applying-templates-to-cells) +- [Применение шаблонов к заголовкам](guides/configuration.md#applying-templates-to-headers) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/detach-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/detach-method.md new file mode 100644 index 0000000..1a71479 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/detach-method.md @@ -0,0 +1,69 @@ +--- +sidebar_label: api.detach() +title: Метод detach +description: Вы можете узнать о методе detach в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, изучайте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.detach() + +## Описание {#description} + +@short: Позволяет удалять/отсоединять обработчики действий + +## Использование {#usage} + +~~~jsx +api.detach(tag: number | string ): void; +~~~ + +## Параметры {#parameters} + +- `tag` - имя тега действия + +### Пример {#example} + +В примере ниже мы добавляем объект со свойством **tag** в обработчик [`api.on()`](api/internal/on-method.md), а затем используем метод `api.detach()`, чтобы прекратить логирование действия [`open-filter`](api/events/open-filter-event.md). + +~~~jsx {31-34} +// создаём Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// добавляем обработчик +if (table.api) { + table.api.on( + "open-filter", + ({ area }) => { + console.log("Opened: " + area); + }, + { tag: "track" } + ); +} + +// отсоединяем обработчик +function stop() { + table.api.detach("track"); +} + +const button = document.createElement("button"); + +button.addEventListener("click", stop); +button.textContent = "Stop logging"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/exec-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/exec-method.md new file mode 100644 index 0000000..d4588b4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/exec-method.md @@ -0,0 +1,83 @@ +--- +sidebar_label: api.exec() +title: Метод exec +description: Вы можете узнать о методе exec в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, изучайте примеры кода и демонстрации, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.exec() + +### Описание {#description} + +@short: Позволяет инициировать внутренние события + +## Использование {#usage} + +~~~jsx +api.exec( + event: string, + config: object +): Promise; +~~~ + +## Параметры {#parameters} + +- `event` - (обязательный) событие, которое необходимо вызвать +- `config` - (обязательный) объект конфигурации с параметрами (см. вызываемое событие) + +## Действия {#actions} + +:::info +Полный список событий Pivot можно найти [**здесь**](api/overview/events-overview.md) +::: + +## Пример {#example} + +В приведённом ниже примере событие [`delete-field`](api/events/delete-field-event.md) инициируется через метод `api.exec()`. Последнее поле удаляется из области **values**. Метод [`api.getState()`](api/internal/getstate-method.md) используется здесь для получения текущего состояния [`config`](api/config/config-property.md) компонента Pivot. Событие будет вызвано по нажатию кнопки. + +~~~jsx {32-35} +// создание Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//вызов методов API: удаление конкретного значения из values в config +function removeLastField() { + if (table.api) { + const state = table.api.getState(); + const config = state.config; + + const count = config.values.length; + + if (count) { + const lastValue = config.values[count - 1]; + + table.api.exec("delete-field", { + area: "values", + id: lastValue.id, // автоматически сгенерированный ID элемента, добавленного в config.values + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md new file mode 100644 index 0000000..a255a4d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md @@ -0,0 +1,71 @@ +--- +sidebar_label: api.getReactiveState() +title: Метод getReactiveState +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о методе getReactiveState. Изучайте руководства разработчика и справочник API, просматривайте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.getReactiveState() + +### Описание {#description} + +@short: Возвращает объект с реактивными свойствами Pivot + +### Использование {#usage} + +~~~jsx +api.getReactiveState(): object; +~~~ + +### Возвращает {#returns} + +Метод возвращает объект со следующими параметрами: + +~~~jsx +{ + config: {}, // текущая конфигурация (строки, столбцы, значения, фильтры) + activeFilter: {}, // объект активного фильтра (если открыт какой-либо фильтр) + columnShape: {}, // конфигурация столбцов сводной таблицы + data: [], // исходные данные + fields: [], // массив полей + filters: {}, // правила фильтрации + headerShape: {}, // настройки заголовка таблицы + predicates: {}, // доступные предикаты по полям + limits: {}, // максимальный лимит на количество строк и столбцов в наборе данных + methods: {}, // методы агрегации данных + tableShape: {}, // настройки таблицы (размеры, итоговая строка, шаблоны) + tableConfig: {}, // параметры конфигурации таблицы (столбцы, данные, размеры, режим дерева, подвал) + configPanel: boolean, // состояние видимости панели конфигурации + readonly: boolean, // включён ли режим только для чтения +} +~~~ + +### Пример {#example} + +~~~jsx {21-26} +// создание Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// подписка на реактивное хранилище конфигурации и вывод его в лог при каждом изменении +const state = table.api.getReactiveState(); + +state.config.subscribe((config) => { + console.log("Pivot config changed. Its current state:", config); +}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md new file mode 100644 index 0000000..4fbc4c4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md @@ -0,0 +1,67 @@ +--- +sidebar_label: api.getState() +title: Метод getState +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о методе getState. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.getState() + +### Описание {#description} + +@short: Возвращает объект со свойствами StateStore компонента Pivot + +### Использование {#usage} + +~~~jsx +api.getState(): object; +~~~ + +### Возвращает {#returns} + +Метод возвращает объект со следующими параметрами: + +~~~jsx +{ + config: {}, // текущая конфигурация (строки, столбцы, значения, фильтры) + activeFilter: {}, // объект активного фильтра (если фильтр открыт) + columnShape: {}, // конфигурация столбцов сводной таблицы + data: [], // исходные данные + fields: [], // массив полей + filters: {}, // правила фильтрации + headerShape: {}, // настройки заголовка таблицы + predicates: {}, // доступные предикаты по полям + limits: {}, // максимальное ограничение на количество строк и столбцов в наборе данных + methods: {}, // методы агрегации данных + tableShape: {}, // настройки таблицы (размеры, итоговая строка, шаблоны) + tableConfig: {}, // параметры конфигурации таблицы (столбцы, данные, размеры, режим дерева, подвал) + configPanel: boolean, // состояние видимости панели конфигурации + readonly: boolean, // включён ли режим только для чтения +} +~~~ + +### Пример {#example} + +~~~jsx {21-22} +// создание Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +const { config } = table.api.getState(); +console.log(config); //вывод состояния конфигурации в консоль +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md new file mode 100644 index 0000000..3730738 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md @@ -0,0 +1,54 @@ +--- +sidebar_label: api.getStores() +title: Метод getStores +description: Вы можете узнать о методе getStores в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, просматривайте примеры кода и живые демо, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.getStores() + +### Описание {#description} + +@short: Возвращает объект со свойствами DataStore компонента Pivot + +### Использование {#usage} + +~~~jsx +api.getStores(): object; +~~~ + +### Возвращает {#returns} + +Метод возвращает объект с параметрами **DataStore**: + +~~~jsx +{ + data: DataStore // ( объект параметров ) +} +~~~ + +### Пример {#example} + +~~~jsx {21-22} +// создаём Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +const stores = table.api.getStores(); +console.log("DataStore:", stores); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md new file mode 100644 index 0000000..74b96b4 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md @@ -0,0 +1,68 @@ +--- +sidebar_label: api.intercept() +title: Метод intercept +description: Вы можете узнать о методе intercept в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, и скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.intercept() + +### Описание {#description} + +@short: Позволяет перехватывать и предотвращать внутренние события + +### Использование {#usage} + +~~~jsx +api.intercept( + event: string, + callback: function, + config?: { tag?: number | string | symbol } +): void; +~~~ + +### Параметры {#parameters} + +- `event` - (обязательный) событие, которое будет вызвано +- `callback` - (обязательный) калбэк для выполнения (аргументы калбэка зависят от вызываемого события) +- `config` - (необязательный) объект, содержащий следующий параметр: + - `tag` - (необязательный) тег действия. Вы можете использовать имя тега для удаления обработчика действия с помощью метода [`detach`](api/internal/detach-method.md) + +### События {#events} + +:::info +Полный список внутренних событий Pivot можно найти [**здесь**](api/overview/main-overview.md#pivot-events). +Используйте метод [`api.on()`](api/internal/on-method.md), если хотите отслеживать действия без их изменения. Чтобы вносить изменения в действия, применяйте метод `api.intercept()`. +::: + +### Пример {#example} + +В примере показано, как сделать так, чтобы все сворачиваемые строки закрывались при инициализации. + +~~~jsx {21-24} +// создаём Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//закрываем все строки при инициализации +table.api.intercept("render-table", (ev) => { + ev.config.data.forEach((row) => (row.open = false)); +}, {tag: "render-table-tag"}); +~~~ + +**Связанные статьи**: [`render-table`](api/events/render-table-event.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/on-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/on-method.md new file mode 100644 index 0000000..f7595f8 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/on-method.md @@ -0,0 +1,72 @@ +--- +sidebar_label: api.on() +title: Метод on +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о методе on. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.on() + +### Описание {#description} + +@short: Позволяет прикрепить обработчик к внутренним событиям + +### Использование {#usage} + +~~~jsx +api.on( + event: string, + handler: function, + config?: { intercept?: boolean, tag?: number | string | symbol } +): void; +~~~ + +### Параметры {#parameters} + +- `event` - (обязательный) событие, которое необходимо отслеживать +- `handler` - (обязательный) прикрепляемый обработчик (аргументы обработчика зависят от вызываемого события) +- `config` - (необязательный) объект со следующими параметрами: + - `intercept` - (необязательный) если при создании слушателя событий задать `intercept: true`, этот слушатель будет выполняться раньше всех остальных + - `tag` - (необязательный) тег действия. Имя тега можно использовать для удаления обработчика действия через метод [`detach`](api/internal/detach-method.md) + +### События {#events} + +:::info +Полный список внутренних событий Pivot можно найти [**здесь**](api/overview/main-overview.md#pivot-events). +Используйте метод `api.on()`, если хотите прослушивать действия без их изменения. Чтобы вносить изменения в действия, применяйте метод [`api.intercept()`](api/internal/intercept-method.md). +::: + +### Пример {#example} + +В примере ниже показано, как вывести метку поля, для которого был активирован фильтр: + +~~~jsx {21-29} +// создание Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + if (ev.id) { + const { config } = table.api.getState(); + const fieldObj = config[ev.area].find((f) => f.id === ev.id); + if (fieldObj) { + console.log("The field for which filter was activated:", fieldObj.label); + } + } +}, {tag: "open-filter-tag"}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md new file mode 100644 index 0000000..59cf40c --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md @@ -0,0 +1,45 @@ +--- +sidebar_label: api.setNext() +title: Метод setNext +description: Вы можете узнать о методе setNext в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# api.setNext() + +### Описание {#description} + +@short: Позволяет добавить действие в цепочку Event Bus + +### Использование {#usage} + +~~~jsx +api.setNext(next: any): void; +~~~ + +### Параметры {#parameters} + +- `next` - (обязательный) действие, которое нужно включить в цепочку **Event Bus** + +### Пример {#example} + +Пример ниже показывает, как использовать метод `api.setNext()` для интеграции пользовательского класса в цепочку Event Bus: + +~~~jsx {13-14} +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +// Предположим, у вас есть пользовательский класс серверного сервиса someServerService +const someServerService = new ServerDataService(server); + +Promise.all([ + fetch(server + "/data").then((res) => res.json()), + fetch(server + "/fields").then((res) => res.json()) +]).then(([data, fields]) => { + table.setConfig({ data, fields }); + + // Интегрируем serverDataService в цепочку Event Bus виджета + table.api.setNext(someServerService); +}); +~~~ + +**Связанные статьи**: [`setConfig`](api/methods/setconfig-method.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md new file mode 100644 index 0000000..5c745a7 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md @@ -0,0 +1,75 @@ +--- +sidebar_label: getTable() +title: Метод getTable +description: В документации по библиотеке DHTMLX JavaScript Pivot вы можете узнать о методе getTable. Изучайте руководства разработчика и справочник API, просматривайте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# getTable() + +### Описание {#description} + +@short: Предоставляет доступ к базовому экземпляру виджета Table в таблице Pivot + +Этот метод используется, когда необходимо получить доступ к базовому экземпляру виджета Table в Pivot. Он обеспечивает прямой доступ к функциональности Table, позволяя выполнять такие операции, как сериализация данных и экспорт в различных форматах. API Table имеет собственный метод `api.exec()`, который может вызывать события [`open-row`](api/table/open-row.md), [`close-row`](api/table/close-row.md), [`export`](api/table/export.md) и [`filter-rows`](api/table/filter-rows.md). + +### Использование {#usage} + +~~~jsx +getTable(wait:boolean): Table | Promise; +~~~ + +### Параметры {#parameters} + +`wait` — определяет, нужно ли ожидать, пока API Table станет доступным в Pivot (необходимо, когда API Table используется в процессе инициализации Pivot). Если значение установлено в **true**, метод возвращает промис с API Table. + +### Пример {#example} + +В приведённом ниже примере мы получаем доступ к API виджета Table и вызываем событие `export` Table по нажатию кнопки с помощью метода [`api.exec()`](api/internal/exec-method.md). + +~~~jsx +// создание Pivot +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// доступ к экземпляру таблицы +let table_instance = table.getTable(); + +function toCSV() { + table_instance.exec("export", { + options: { + format: "csv", + cols: ";" + } + }); +} + +const exportButton = document.createElement("button"); + +exportButton.addEventListener("click", toCSV); +exportButton.textContent = "Export"; + +document.body.appendChild(exportButton); +~~~ + +**Связанные статьи**: + +- [`close-row`](api/table/close-row.md) +- [`export`](api/table/export.md) +- [`filter-rows`](api/table/filter-rows.md) +- [`open-row`](api/table/open-row.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md new file mode 100644 index 0000000..18036e5 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md @@ -0,0 +1,73 @@ +--- +sidebar_label: setConfig() +title: setConfig() +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о методе setConfig(). Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# setConfig() + +### Описание {#description} + +@short: Обновляет текущую конфигурацию виджета Pivot + +Метод используется для обновления текущей конфигурации виджета Pivot. Он полезен, когда необходимо обновить базовый набор данных виджета. Метод сохраняет все ранее заданные параметры, которые явно не указаны в вызове `setConfig`. + +### Использование {#usage} + +~~~jsx +setConfig(config: { [key:any]: any }): void; +~~~ + +### Параметры {#parameters} + +- `config` - (обязательный) объект конфигурации Pivot. Полный список свойств см. [здесь](api/overview/properties-overview.md) + +:::important +Метод изменяет только переданные параметры. Он уничтожает текущий компонент и инициализирует новый. +::: + +### Пример {#example} + +~~~jsx {21-41} +// создание Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// обновление параметров конфигурации +table.setConfig({ + config: { + rows: ["studio", "genre", "duration"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + { + field: "type", + method: "count" + } + ] + } +}); +~~~ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md new file mode 100644 index 0000000..7c8d785 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md @@ -0,0 +1,56 @@ +--- +sidebar_label: setLocale() +title: setLocale() +description: Вы можете узнать о методе setLocale() в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник по API, изучайте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# setLocale() + +### Описание {#description} + +@short: Применяет новую локаль к Pivot + +### Использование {#usage} + +~~~jsx +setLocale(null | locale?: object): void; +~~~ + +### Параметры {#parameters} + +- `null` - (необязательный) сбрасывает локаль на значение по умолчанию (английский) +- `locale` - (необязательный) объект с данными новой применяемой локали + +### Пример {#example} + +~~~jsx +// создаём Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// применяем локаль "de" к Pivot +table.setLocale(pivot.locales.de); + +// применяем локаль по умолчанию к Pivot +table.setLocale(); // или setLocale(null); +~~~ + +**Связанные статьи**: +- [Локализация](guides/localization.md) +- [`locale`](api/config/locale-property.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md new file mode 100644 index 0000000..ed6b768 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md @@ -0,0 +1,55 @@ +--- +sidebar_label: showConfigPanel() +title: showConfigPanel() +description: Вы можете узнать о методе showConfigPanel() в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, изучайте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# showConfigPanel() + +### Описание {#description} + +@short: Показывает или скрывает панель настройки + +Этот метод может быть полезен, когда необходимо управлять видимостью панели настройки без участия пользователя. Например, можно скрывать или отображать панель в зависимости от какого-либо другого взаимодействия или состояния в приложении. + +### Использование {#usage} + +~~~jsx +showConfigPanel({mode: boolean}): void; +~~~ + +### Параметры {#parameters} + +- `mode` (boolean) - (обязательный) если значение установлено в **true** (по умолчанию), панель настройки отображается; если установлено в **false**, панель настройки скрыта + +### Пример {#example} + +~~~jsx {21-23} +// создаём Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.showConfigPanel ({ + mode: false +}) +~~~ + +**Связанные статьи**: +- [событие `show-config-panel`](api/events/show-config-panel-event.md) +- [свойство `configPanel`](api/config/configpanel-property.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/events-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/events-overview.md new file mode 100644 index 0000000..16119a0 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/events-overview.md @@ -0,0 +1,19 @@ +--- +sidebar_label: Обзор событий +title: Обзор событий +description: Вы можете ознакомиться с обзором событий JavaScript Pivot в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства для разработчиков и справочник API, попробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор событий {#events-overview} + +| Название | Описание | +| ------------------------------------------------- | ----------------------------------------------- | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md new file mode 100644 index 0000000..fe0d9a9 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md @@ -0,0 +1,15 @@ +--- +sidebar_label: Методы Event Bus +title: Методы Event Bus +description: В документации библиотеки DHTMLX JavaScript Pivot вы найдёте обзор методов внутренней шины событий. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор методов Event Bus {#event-bus-methods-overview} + +| Название | Описание | +| ---------------------------------------------- | ------------------------------------------------- | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md new file mode 100644 index 0000000..28e5d5d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md @@ -0,0 +1,13 @@ +--- +sidebar_label: State methods +title: Методы состояния +description: В документации библиотеки DHTMLX JavaScript Pivot можно найти обзор методов внутреннего состояния JavaScript Pivot. Изучайте руководства для разработчиков и справочник API, пробуйте примеры кода и живые демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор методов состояния {#state-methods-overview} + +| Название | Описание | +| ---------------------------------------------- | -------------------------------------------------- | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/main-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/main-overview.md new file mode 100644 index 0000000..0d6346d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/main-overview.md @@ -0,0 +1,80 @@ +--- +sidebar_label: Обзор API +title: Обзор API +description: Вы можете ознакомиться с обзором API JavaScript Pivot в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор API {#api-overview} + +## Конструктор Pivot {#pivot-constructor} + +~~~jsx +new pivot.Pivot("#root", { + // параметры конфигурации +}); +~~~ + +**Параметры**: + +- HTML-контейнер (идентификатор HTML-контейнера) +- объект параметров конфигурации ([смотрите здесь](#pivot-properties)) + +## Методы Pivot {#pivot-methods} + +| Название | Описание | +| ------------------------------------------- | ------------------------------------------ | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | + +## Внутреннее API Pivot {#pivot-internal-api} + +### Методы Event Bus {#event-bus-methods} + +| Название | Описание | +| :------------------------------------ | :------------------------------------------- | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | + +### Методы состояния {#state-methods} + +| Название | Описание | +| :---------------------------------------------- | :------------------------------------------------- | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | + +## События Pivot {#pivot-events} + +| Название | Описание | +| :------------------------------------------------ | :---------------------------------------------- | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | + +## Свойства Pivot {#pivot-properties} + +| Название | Описание | +| :------------------------------------------------- | :----------------------------------------------- | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md new file mode 100644 index 0000000..51d4f9f --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md @@ -0,0 +1,14 @@ +--- +sidebar_label: Обзор методов +title: Обзор методов +description: В документации библиотеки DHTMLX JavaScript Pivot доступен обзор методов JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор методов + +| Название | Описание | +| ------------------------------------------- | ----------------------------------------------- | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md new file mode 100644 index 0000000..02c2c76 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md @@ -0,0 +1,24 @@ +--- +sidebar_label: Обзор свойств +title: Обзор свойств +description: В документации библиотеки DHTMLX JavaScript Pivot доступен обзор свойств JavaScript Pivot. Изучите руководства разработчика и справочник по API, ознакомьтесь с примерами кода и живыми демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор свойств {#properties-overview} + +Для настройки **Pivot** обратитесь к разделу [Конфигурация](guides/configuration.md). + +| Название | Описание | +| -------------------------------------------------- | ------------------------------------------------ | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md new file mode 100644 index 0000000..ec8271e --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md @@ -0,0 +1,16 @@ +--- +sidebar_label: Обзор событий таблицы +title: Обзор событий таблицы +description: В документации библиотеки DHTMLX JavaScript Pivot вы найдёте обзор событий таблицы. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор событий таблицы + +Метод [`getTable`](api/methods/gettable-method.md) API Pivot позволяет получить доступ к экземпляру виджета Table внутри Pivot и выполнить следующие события таблицы: + +| Название | Описание | +| ------------------------------------------------- | ----------------------------------------------- | +| [](api/table/close-row.md) | @getshort(../table/close-row.md) | +| [](api/table/export.md) | @getshort(../table/export.md) | +| [](api/table/filter-rows.md) | @getshort(../table/filter-rows.md) | +| [](api/table/open-row.md) | @getshort(../table/open-row.md) | diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/table/close-row.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/close-row.md new file mode 100644 index 0000000..05ac7a9 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/close-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: close-row +title: close-row +description: Вы можете узнать о событии close-row в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot +--- + +# close-row + +### Описание {#description} + +@short: Срабатывает при закрытии (сворачивании) строки + +Чтобы вызвать событие Table, необходимо получить доступ к базовому экземпляру виджета Table внутри Pivot через метод [`getTable`](api/methods/gettable-method.md). Режим дерева должен быть включён через свойство [`tableShape`](api/config/tableshape-property.md). + +### Использование {#usage} + +```jsx {} +"close-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующими параметрами: + +- `id` - (обязательный) идентификатор строки, содержащей вложенные строки +- `nested` - (необязательный) если задано значение **true**, все вложенные элементы будут свёрнуты + +:::note +Если `id` равно 0, а `nested` — **true**, все строки в таблице будут свёрнуты +::: + +### Пример {#example} + +Приведённый ниже сниппет демонстрирует, как открывать/закрывать все строки по нажатию кнопки: + + + +**Связанные статьи**: +- [`getTable`](api/methods/gettable-method.md) +- [Разворачивание/сворачивание всех строк](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/table/export.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/export.md new file mode 100644 index 0000000..bdbde0c --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/export.md @@ -0,0 +1,109 @@ +--- +sidebar_label: export +title: export +description: Вы можете узнать о событии export в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, изучайте примеры кода и живые демо, загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot +--- + +# export + +### Описание {#description} + +@short: Срабатывает при экспорте данных + +Чтобы вызвать событие Table, необходимо получить доступ к экземпляру Table внутри Pivot через метод [`getTable`](api/methods/gettable-method.md). + +### Использование {#usage} + +```jsx +"export": ({ + options: { + format: "csv" | "xlsx", + fileName?: string, + header?: boolean, + footer?: boolean, + download?: boolean, + + /* XLSX settings*/ + styles?: boolean | { + header?: { + fontWeight?: "bold", + color?: string, + background?: string, + align?: "left"|"right"|"center", + borderBottom?: string, + borderRight?: string, + } + lastHeaderCell?: { /* same as header */ }, + cell?: { /* same as header */ }; + firstFooterCell?: { /* same as header */ }, + footer?: {/* same as header */}, + } + cellTemplate?: (value: any, row: any, column: object ) + => string | null, + headerCellTemplate?: (text: string, cell: object, column: object, type: "header"| "footer") + => string | null, + cellStyle?: (value: any, row: any, column: object) + => { format: string; align: "left"|"right"|"center" } | null, + headerCellStyle?: (text: string, cell: object, column: object, type: "header"| "footer") + => { format: string; align: "left"|"right"|"center" } | null, + sheetName?: string, + + /* CSV settings */ + rows: string, + cols: string, + }, + result?: any, +}) => boolean|void; +``` + +Действие `export` виджета Table имеет следующие параметры, которые можно настроить под свои нужды: + +- `options` - объект с параметрами экспорта; параметры различаются в зависимости от типа формата +- `result` - результат экспортированных данных Excel или CSV (обычно Blob или файл в зависимости от параметра `download`) + + **Общие параметры для обоих форматов ("csv" и "xlsx")**: + + - `format` (string) - (необязательный) формат экспорта: "csv" или "xlsx" + - `fileName` (string) - (необязательный) имя файла (по умолчанию "data") + - `header` (boolean) - (необязательный) определяет, нужно ли экспортировать заголовок (по умолчанию **true**) + - `footer` (boolean) - (необязательный) определяет, нужно ли экспортировать подвал (по умолчанию **true**) + - `download` (boolean) - (необязательный) определяет, загружать ли файл. По умолчанию **true**. Если задано **false**, файл не будет загружен, а данные Excel или CSV (Blob) будут доступны как `ev.result` + + **Параметры, специфичные для формата "xlsx"**: + + - `sheetName` (string) - имя листа Excel (по умолчанию "data") + - `styles` (boolean или объект) - если задано **false**, таблица экспортируется без стилей; можно настроить с помощью набора свойств стиля: + - `header` - объект со следующими настройками для ячеек заголовка: + - `fontWeight` (string) - (необязательный) может быть задано "bold"; если не задано, шрифт будет обычным + - `color` (string) - (необязательный) цвет текста в заголовке + - `background` (string) - (необязательный) цвет фона заголовка + - `align` - (необязательный) выравнивание текста: "left"|"right"|"center". Если не задано, применяется выравнивание, установленное в Excel + - `borderBottom` (string) - (необязательный) стиль нижней границы + - `borderRight` (string) - (необязательный) стиль правой границы (например, *borderRight: "0.5px solid #dfdfdf"*) + - `lastHeaderCell` - свойства стиля для последней строки ячеек заголовка. Свойства аналогичны *header* + - `cell` - свойства стиля для ячеек тела таблицы. Свойства аналогичны *header* + - `firstFooterCell` - свойства стиля для первой строки ячеек подвала. Свойства аналогичны *header* + - `footer` - свойства стиля для ячеек подвала. Свойства аналогичны *header* + - `cellTemplate` - функция для настройки экспортируемого значения каждой ячейки. Принимает значение, объекты строки и столбца в качестве параметров и возвращает пользовательское значение для экспорта + - `headerCellTemplate` - функция, настраивающая значение ячейки заголовка или подвала при экспорте. Вызывается с текстом, объектом ячейки заголовка, объектом столбца и типом ячейки ("header" или "footer"). Позволяет изменять экспортируемые значения заголовка/подвала + - `cellStyle` - функция для настройки стиля и формата отдельных ячеек при экспорте. Принимает значение, объекты строки и столбца в качестве параметров и должна возвращать объект со свойствами стиля (например, выравниванием или форматом) + - `headerCellStyle` - аналогична `cellStyle`, но предназначена для ячеек заголовка и подвала. Принимает текст, объект ячейки заголовка, объект столбца и тип ("header" или "footer") и возвращает свойства стиля + :::note + По умолчанию для формата "xlsx" поля дат и чисел экспортируются как необработанные значения с форматом по умолчанию или форматом, заданным через свойство [`fields`](api/config/fields-property.md). Однако если для поля задан шаблон (см. свойство [`tableShape`](api/config/tableshape-property.md)), экспортируется отображаемое значение, определённое этим шаблоном. Если заданы и шаблон, и `format`, настройки шаблона переопределяют настройки формата. + ::: + + **Параметры, специфичные для формата "csv"**: + + - `rows` (string) - (необязательный) разделитель строк, по умолчанию "\n" + - `cols` (string) - (необязательный) разделитель столбцов, по умолчанию "\t" + +## Пример {#example} + +В этом примере показано, как экспортировать данные: + + + +**Связанные статьи**: +- [`getTable`](api/methods/gettable-method.md) +- [Экспорт данных](guides/exporting-data.md) +- [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/table/filter-rows.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/filter-rows.md new file mode 100644 index 0000000..2f55806 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/filter-rows.md @@ -0,0 +1,35 @@ +--- +sidebar_label: filter-rows +title: filter-rows +description: Вы можете узнать о событии filter-rows в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot +--- + +# filter-rows + +### Описание {#description} + +@short: Срабатывает при фильтрации данных + +Чтобы вызвать событие Table, необходимо получить доступ к экземпляру Table внутри Pivot с помощью метода [`getTable`](api/methods/gettable-method.md). + +### Использование {#usage} + +```jsx {} +"filter-rows": ({ + filter?: any +}) => boolean|void; +``` + +### Параметры {#parameters} + +Калбэк действия принимает объект со следующими параметрами: + +- `filter` - (необязательный) любая функция фильтрации, которая принимает каждый элемент из массива данных и возвращает **true** или **false** для каждого элемента + +### Пример {#example} + +Фрагмент ниже демонстрирует, как фильтровать агрегированные (видимые) данные в теле таблицы по значению ввода: + + + +**Связанная статья**: [`getTable`](api/methods/gettable-method.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/api/table/open-row.md b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/open-row.md new file mode 100644 index 0000000..872c11e --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/api/table/open-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: open-row +title: open-row +description: В документации JavaScript-библиотеки DHTMLX Pivot вы можете узнать о событии open-row. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, скачивайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot +--- + +# open-row + +### Описание {#description} + +@short: Срабатывает при открытии (разворачивании) строки + +Чтобы вызвать событие Table, необходимо получить доступ к экземпляру Table внутри Pivot через метод [`getTable`](api/methods/gettable-method.md). Режим дерева должен быть включён через свойство [`tableShape`](api/config/tableshape-property.md). + +### Использование {#usage} + +```jsx {} +"open-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### Параметры {#parameters} + +Колбэк действия принимает объект со следующими параметрами: + +- `id` - (обязательный) идентификатор строки, содержащей вложенные строки +- `nested` - (необязательный) если установлено значение **true**, все вложенные элементы будут развёрнуты + +:::note +Если `id` равен 0, а `nested` установлено в **true**, все строки в таблице будут развёрнуты +::: + +### Пример {#example} + +Фрагмент кода ниже демонстрирует, как открывать/закрывать все строки по нажатию кнопки: + + + +**Связанные статьи**: +- [`getTable`](api/methods/gettable-method.md) +- [Разворачивание/сворачивание всех строк](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/add_remove.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/add_remove.png new file mode 100644 index 0000000..81dcb52 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/add_remove.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/apply_filter.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/apply_filter.png new file mode 100644 index 0000000..53905a7 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/apply_filter.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/config_panel.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/config_panel.png new file mode 100644 index 0000000..41b7568 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/config_panel.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/filter.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/filter.png new file mode 100644 index 0000000..b4b1599 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/filter.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/filter_applied.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/filter_applied.png new file mode 100644 index 0000000..9ed7479 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/filter_applied.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/operations.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/operations.png new file mode 100644 index 0000000..80f6f79 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/operations.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/pivot-main.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/pivot-main.png new file mode 100644 index 0000000..5eaa953 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/pivot-main.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/priority.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/priority.png new file mode 100644 index 0000000..a827e01 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/priority.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/table.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/table.png new file mode 100644 index 0000000..f0fb3a9 Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/table.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/assets/trial_pivot.png b/i18n/ru/docusaurus-plugin-content-docs/current/assets/trial_pivot.png new file mode 100644 index 0000000..f2e21cf Binary files /dev/null and b/i18n/ru/docusaurus-plugin-content-docs/current/assets/trial_pivot.png differ diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/configuration.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/configuration.md new file mode 100644 index 0000000..8106fc9 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/configuration.md @@ -0,0 +1,740 @@ +--- +sidebar_label: Конфигурация +title: Конфигурация +description: Вы можете узнать о конфигурации в документации библиотеки DHTMLX JavaScript Pivot. Просматривайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Конфигурация + +Настройте таблицу Pivot и панель конфигурации с помощью следующего API: + +- [`config`](api/config/config-property.md) — определяет структуру таблицы Pivot и способ агрегации данных +- [`render-table`](api/events/render-table-event.md) — изменяет конфигурацию таблицы на лету +- [`tableShape`](api/config/tableshape-property.md) — настраивает внешний вид таблицы Pivot +- [`columnShape`](api/config/columnshape-property.md) — настраивает внешний вид и поведение столбцов +- [`headerShape`](api/config/headershape-property.md) — настраивает внешний вид и поведение заголовков +- [`configPanel`](api/config/configpanel-property.md) — управляет видимостью панели конфигурации +- [`setLocale`](api/methods/setlocale-method.md) — применяет локаль (см. [Локализация](guides/localization.md)) +- [`data`](api/config/data-property.md), [`fields`](api/config/fields-property.md) — загружают данные и метаданные полей +- [`predicates`](api/config/predicates-property.md) — предварительно обрабатывают данные перед агрегацией +- [`methods`](api/config/methods-property.md) — определяют пользовательские методы агрегации +- [`limits`](api/config/limits-property.md) — ограничивают количество строк и столбцов в итоговом наборе данных + +Инструкции по работе с данными см. в разделе [Работа с данными](guides/working-with-data.md). + +Вы можете настроить следующие элементы таблицы Pivot: + +- столбцы и строки +- заголовки и подвалы +- ячейки +- размеры таблицы + +## Изменение размеров таблицы {#resizing-the-table} + +Используйте свойство [`tableShape`](api/config/tableshape-property.md), чтобы изменить размер строк, столбцов, заголовка и подвала. + +Следующий фрагмент кода показывает размеры по умолчанию: + +~~~jsx +const sizes = { + rowHeight: 34, + headerHeight: 30, + footerHeight: 30, + columnWidth: 150 +}; +~~~ + +Следующий фрагмент кода переопределяет размеры по умолчанию: + +~~~jsx {4-11} +const table = new pivot.Pivot("#root", { + fields, + data, + tableShape: { + sizes: { + rowHeight: 44, + headerHeight: 60, + footerHeight: 30, + columnWidth: 170 + } + }, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +:::info +Чтобы задать ширину конкретных столбцов, используйте параметр `width` свойства [`columnShape`](api/config/columnshape-property.md). +::: + +## Автоматическое изменение ширины столбцов по содержимому + +Используйте параметр `autoWidth` свойства [`columnShape`](api/config/columnshape-property.md), чтобы вычислять ширину столбцов автоматически. Все подпараметры `autoWidth` являются необязательными — полные описания см. в справочнике [`columnShape`](api/config/columnshape-property.md). + +Объект `autoWidth` принимает следующие параметры: + +- `columns` — объект, определяющий, для каких полей вычисляется ширина автоматически +- `auto` — подстраивает ширину под заголовок, содержимое ячейки или под оба варианта +- `maxRows` — количество строк данных, анализируемых для определения размера столбца (по умолчанию: 20) +- `firstOnly` — если `true` (по умолчанию), каждое поле анализируется только один раз. Когда несколько столбцов основаны на одном поле (например, `oil` с `count` и `oil` с `sum`), анализируется только первый столбец, а остальные наследуют его ширину + +Следующий фрагмент кода включает `autoWidth` для четырёх полей и отключает `firstOnly`, чтобы каждый столбец получил собственное измерение: + +~~~jsx {18-30} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + autoWidth: { + // вычислять ширину столбца для этих полей + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + // анализировать все поля + firstOnly: false + } + } +}); +~~~ + +## Применение шаблонов к ячейкам {#applying-templates-to-cells} + +### Добавление шаблонов через tableShape + +Используйте параметр `templates` свойства [`tableShape`](api/config/tableshape-property.md), чтобы отображать значения ячеек через функцию. Каждый ключ — это идентификатор поля, а каждое значение — функция, возвращающая строку. Все столбцы, основанные на указанном поле, получают этот шаблон. + +В примере ниже к ячейкам `state` применяется шаблон, который отображает объединённое название штата (полное название и аббревиатура): + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", + // другие значения +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // настроить значения ячеек "state" + state: v => v + ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // другие значения + ], + }, + fields, +}); +~~~ + +### Добавление шаблона через хелпер template {#adding-a-template-via-the-template-helper} + +Чтобы вставить HTML-содержимое в ячейки тела таблицы, используйте хелпер [`pivot.template`](api/helpers/template.md) и присвойте результат свойству `cell` объекта столбца. Применяйте шаблон непосредственно перед отрисовкой таблицы, перехватывая событие [`render-table`](api/events/render-table-event.md) с помощью метода [`api.intercept`](api/internal/intercept-method.md). + +В примере ниже в ячейки тела добавляются иконки (звезда или флаг) в зависимости от поля (`id`, `user_score`): + +~~~js +function cellTemplate(value, method, row, column) { + const field = column.fields ? column.fields[row.$level] : column.field; + + if (field === "id") { + return idTemplate(value); + } + + if (field === "user_score") { + return scoreTemplate(value); + } + + return value; +} + +function idTemplate(value) { + const name = value?.toString().split("-")[0]; + return ` ${value}`; +} + +function scoreTemplate(value) { + return ` ${value}`; +} + +widget.api.intercept("render-table", ({ config: tableConfig }) => { + tableConfig.columns = tableConfig.columns.map((c) => { + if (c.area === "rows") { + // применить шаблон к ячейкам столбца из области "rows" + c.cell = pivot.template(({ value, method, row, column }) => cellTemplate(value, method, row, column)); + } + return c; + }); +}); +~~~ + +## Применение шаблонов к заголовкам {#applying-templates-to-headers} + +### Добавление шаблонов через headerShape + +Чтобы управлять форматом текста в заголовках, используйте параметр `template` свойства [`headerShape`](api/config/headershape-property.md). Параметр представляет собой функцию, которая: + +- принимает метку поля, его ID и подпись (название метода, если есть) +- возвращает обработанное значение + +Шаблон по умолчанию: + +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +Без пользовательского шаблона поля области `values` отображают метку и метод (например, `Oil(count)`), а поля других областей отображают значение `label`. Шаблон [`predicates`](api/config/predicates-property.md) переопределяет шаблон `headerShape`. + +В примере ниже текст заголовка преобразуется в нижний регистр, давая такие метки, как `profit (sum)`: + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // пользовательский шаблон для текста заголовка + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // другие значения + ], + }, + fields, +}); +~~~ + +### Добавление шаблонов через хелпер template + +Чтобы вставить HTML-содержимое в ячейки заголовков, используйте хелпер [`pivot.template`](api/helpers/template.md) и присвойте результат свойству `cell` объекта ячейки заголовка. Применяйте шаблон непосредственно перед отрисовкой таблицы, перехватывая событие [`render-table`](api/events/render-table-event.md) с помощью метода [`api.intercept`](api/internal/intercept-method.md). + +В примере ниже иконки добавляются к: + +- меткам заголовков на основе имени поля (например, `id` получает иконку глобуса) +- заголовкам столбцов на основе значения ячейки (цветные стрелки-индикаторы в зависимости от значения `status`) + +~~~jsx +function rowsHeaderTemplate(value, field) { + let icon = ""; + if (field === "id") icon = ""; + if (field === "user_score") icon = ""; + return `${value} ${icon}`; +} + +function statusTemplate(value) { + let icon = ""; + if (value === "Up") icon = ""; + if (value === "Down") icon = ""; + return `${value} ${icon}`; +} + +widget.api.intercept("render-table", ({ config: tableConfig }) => { + tableConfig.columns = tableConfig.columns.map((c) => { + if (c.area === "rows") { + // применить шаблон к первой строке заголовка столбцов из области "rows" + c.header[0].cell = pivot.template(({ value, field }) => rowsHeaderTemplate(value, field)); + } else { + // ячейки заголовка, отображающие значения из поля "status" + const headerCell = c.header.find((h) => h.field === "status"); + if (headerCell) { + headerCell.cell = pivot.template(({ value }) => statusTemplate(value)); + } + } + return c; + }); +}); +~~~ + +## Сворачиваемые столбцы + +Чтобы пользователи могли сворачивать и разворачивать столбцы под общим заголовком, установите параметр `collapsible` свойства [`headerShape`](api/config/headershape-property.md) в `true`. + +Следующий фрагмент кода включает сворачиваемые заголовки столбцов: + +~~~jsx {4-6} +const table = new pivot.Pivot("#root", { + fields, + data, + headerShape: { + collapsible: true, + }, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## Фиксация столбцов {#freezing-columns} + +Зафиксируйте столбцы слева или справа, чтобы они оставались видимыми при прокрутке остальной части таблицы. Используйте параметр `split` свойства [`tableShape`](api/config/tableshape-property.md) и установите `left` или `right` в `true`. + +### Фиксация столбцов слева + +Когда `split.left` равно `true`, количество зафиксированных столбцов соответствует количеству полей `rows` в свойстве [`config`](api/config/config-property.md). В древовидном режиме фиксируется только один столбец независимо от количества полей `rows`. + +Следующий фрагмент кода фиксирует один столбец слева (определено одно поле `rows`): + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + split: {left: true } + } +}); +~~~ + +Чтобы задать пользовательское количество фиксированных столбцов, подпишитесь на событие [`render-table`](api/events/render-table-event.md) и переопределите `tableConfig.split`. Избегайте разделения столбцов с объединёнными ячейками (colspan). + +Следующий фрагмент кода фиксирует слева все столбцы `rows` плюс удвоенное количество полей `values`: + +~~~jsx {19-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + { + field: "oil", + method: "sum" + }, + { + field: "oil", + method: "count" + } + ] + } +}); +table.api.on("render-table", ({ config: tableConfig }) => { + const { config } = table.api.getState(); + + tableConfig.split = { + left: config.rows.length + config.values.length * 2 + }; +}); +~~~ + +### Фиксация столбцов справа {#freezing-columns-on-the-right} + +Установите `split.right` в `true`, чтобы зафиксировать итоговые столбцы справа. + +Следующий фрагмент кода фиксирует итоговый столбец справа: + +~~~jsx {4-7} +const widget = new pivot.Pivot("#pivot", { + fields, + data: dataset, + tableShape:{ + split: {right: true}, + totalColumn: true, + }, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +Чтобы зафиксировать произвольное количество столбцов справа, подпишитесь на событие [`render-table`](api/events/render-table-event.md) и переопределите `tableConfig.split`. Избегайте разделения столбцов с объединёнными ячейками (colspan). + +Следующий фрагмент кода фиксирует справа столько столбцов, сколько полей в `values`: + +~~~jsx {20-25} +const widget = new pivot.Pivot("#pivot", { + fields, + data: dataset, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); + +widget.api.on("render-table", ({ config: tableConfig }) => { + const { config } = widget.api.getState(); + tableConfig.split = { + right: config.values.length, + } +}) +~~~ + +## Сортировка в столбцах + +Сортировка в интерфейсе включена по умолчанию — пользователи нажимают на заголовок столбца для сортировки. Чтобы отключить её, установите параметр `sort` свойства [`columnShape`](api/config/columnshape-property.md) в `false`. + +Следующий фрагмент кода отключает сортировку в интерфейсе: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +Подробнее о сортировке по умолчанию, пользовательских компараторах и обновлениях во время выполнения см. в разделе [Сортировка данных](guides/working-with-data.md#sorting-data). + +## Включение древовидного режима {#enabling-the-tree-mode} + +Древовидный режим отображает данные иерархически с раскрываемыми строками. Установите параметр `tree` свойства [`tableShape`](api/config/tableshape-property.md) в `true` (по умолчанию `false`). Первое поле массива `rows` в [`config`](api/config/config-property.md) становится родительской строкой. + +Следующий фрагмент кода включает древовидный режим с `studio` в качестве родителя и `genre` в качестве вложенных строк: + +~~~jsx {3} +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true + }, + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "max" + } + ] + } +}); +~~~ + +## Развёртывание и свёртывание всех строк {#expandingcollapsing-all-rows} + +Чтобы программно развернуть или свернуть все строки, включите древовидный режим через свойство [`tableShape`](api/config/tableshape-property.md). Затем получите экземпляр виджета Table с помощью метода [`getTable`](api/methods/gettable-method.md) и вызовите событие [`open-row`](api/table/open-row.md) или [`close-row`](api/table/close-row.md) через метод `api.exec` таблицы. + +В примере ниже отрисовываются кнопки «Открыть все» и «Закрыть все», которые разворачивают или сворачивают все ветки в древовидном режиме: + +~~~jsx +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true + }, + fields, + data: dataset, + config: { + rows: ["type", "studio"], + columns: [], + values: [ + { + field: "score", + method: "max" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + }, + { + field: "episodes", + method: "count" + } + ] + } +}); + +const api = table.api; +const tableInstance = api.getTable(); +// держать все ветки таблицы закрытыми при отрисовке +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // вернуть false здесь, чтобы предотвратить отрисовку таблицы + // return false; +}); + +function openAll() { + tableInstance.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableInstance.exec("close-row", { id: 0, nested: true }); +} + +const openAllButton = document.createElement("button"); +openAllButton.addEventListener("click", openAll); +openAllButton.textContent = "Open all"; + +const closeAllButton = document.createElement("button"); +closeAllButton.addEventListener("click", closeAll); +closeAllButton.textContent = "Close all"; + +document.body.appendChild(openAllButton); +document.body.appendChild(closeAllButton); +~~~ + +## Изменение ориентации текста заголовков + +Чтобы повернуть текст заголовков из горизонтального в вертикальное положение, установите параметр `vertical` свойства [`headerShape`](api/config/headershape-property.md) в `true`. + +Следующий фрагмент кода отрисовывает вертикальный текст заголовков: + +~~~jsx {4-6} +const table = new pivot.Pivot("#root", { + fields, + data, + headerShape: { + vertical: true + }, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## Управление видимостью панели конфигурации {#controlling-visibility-of-configuration-panel} + +Панель конфигурации отображается по умолчанию. Пользователи могут переключать её с помощью кнопки **Скрыть настройки** / **Показать настройки**. Управляйте панелью программно через свойство [`configPanel`](api/config/configpanel-property.md), событие [`show-config-panel`](api/events/show-config-panel-event.md) или метод [`showConfigPanel`](api/methods/showconfigpanel-method.md). + +### Скрыть панель конфигурации + +Чтобы скрыть панель при инициализации, установите свойство [`configPanel`](api/config/configpanel-property.md) в `false`. + +Следующий фрагмент кода инициализирует Pivot со скрытой панелью: + +~~~jsx +// панель конфигурации скрыта при инициализации +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + configPanel: false, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +Чтобы переключить панель во время выполнения, вызовите событие [`show-config-panel`](api/events/show-config-panel-event.md) с помощью метода [`api.exec`](api/internal/exec-method.md) и установите параметр `mode` в `false`. + +Следующий фрагмент кода скрывает панель после инициализации: + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +// скрыть панель конфигурации +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +### Отключение переключения по умолчанию + +Чтобы полностью заблокировать стандартную кнопку переключения, перехватите событие [`show-config-panel`](api/events/show-config-panel-event.md) с помощью метода [`api.intercept`](api/internal/intercept-method.md) и верните `false`. + +Следующий фрагмент кода отключает кнопку переключения: + +~~~jsx {20-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.intercept("show-config-panel", () => { + return false; +}); +~~~ + +В качестве альтернативного API используйте метод [`showConfigPanel`](api/methods/showconfigpanel-method.md). + +### Действия с полями на панели + +Панель конфигурации поддерживает следующие операции с полями: + +- [`add-field`](api/events/add-field-event.md) — добавить поле в область +- [`delete-field`](api/events/delete-field-event.md) — удалить поле из области +- [`update-field`](api/events/update-field-event.md) — обновить метод или настройки поля +- [`move-field`](api/events/move-field-event.md) — изменить порядок полей внутри области + +**Связанные примеры**: +- [Pivot 2. Добавление текстовых шаблонов для ячеек таблицы и заголовков](https://snippet.dhtmlx.com/n9ylp6b2) +- [Pivot 2. Пользовательские фиксированные столбцы (произвольное количество)](https://snippet.dhtmlx.com/53erlmgp) +- [Pivot 2. Развёртывание и свёртывание всех строк](https://snippet.dhtmlx.com/i4mi6ejn) +- [Pivot 2. Фиксированные столбцы слева и справа](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. Сортировка](https://snippet.dhtmlx.com/j7vtief6) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/exporting-data.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/exporting-data.md new file mode 100644 index 0000000..54c9192 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/exporting-data.md @@ -0,0 +1,45 @@ +--- +sidebar_label: Экспорт данных +title: Экспорт данных +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете изучить, как экспортировать данные. Просматривайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Экспорт данных {#exporting-data} + +Pivot экспортирует данные таблицы в форматах XLSX или CSV через встроенный виджет Table. Получите экземпляр Table с помощью метода [`getTable`](api/methods/gettable-method.md), затем вызовите событие [`export`](api/table/export.md) через метод [`api.exec`](api/internal/exec-method.md) таблицы. + +Пример ниже получает экземпляр Table и вызывает событие `export` в форматах CSV и XLSX: + +~~~jsx +const widget = new pivot.Pivot("#root", { /* settings */ }); + +widget.getTable().exec("export", { + options: { + format: "csv", + cols: ";" + } +}); + +widget.getTable().exec("export", { + options: { + format: "xlsx", + fileName: "My Report", + sheetName: "Quarter 1" + } +}); +~~~ + +:::tip +Метод [`getTable`](api/methods/gettable-method.md) принимает необязательный булев параметр `wait`. Передайте `true`, чтобы получить промис, который разрешится после того, как API Table станет доступным. Это полезно, когда API Table должен быть готов в процессе инициализации Pivot. +::: + +## Пример {#example} + +Фрагмент ниже выполняет экспорт данных: + + + +**Related articles**: + +- [Форматирование дат](guides/localization.md#date-formatting) +- [`export`](api/table/export.md) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/initialization.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/initialization.md new file mode 100644 index 0000000..8ee085b --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/initialization.md @@ -0,0 +1,86 @@ +--- +sidebar_label: Инициализация +title: Инициализация +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать об инициализации компонента. Изучите руководства разработчика и справочник API, попробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Инициализация + +В этом руководстве описано, как создать Pivot на странице и расширить приложение возможностями сводной таблицы. Выполните следующие шаги, чтобы получить готовый к использованию компонент: + +1. [Подключите исходные файлы Pivot на странице](#include-source-files). +2. [Создайте контейнер для Pivot](#create-a-container). +3. [Инициализируйте Pivot с помощью конструктора](#initialize-pivot). + +## Подключение исходных файлов {#include-source-files} + +Для работы приложения Pivot на странице необходимы два исходных файла. Инструкции по загрузке пакета см. в разделе [Загрузка пакетов](how-to-start.md#step-1-downloading-and-installing-packages). + +Подключите следующие файлы: + +- *pivot.js* +- *pivot.css* + +Укажите правильные относительные пути к исходным файлам: + +~~~html title="index.html" + + +~~~ + +## Создание контейнера {#create-a-container} + +Pivot отрисовывается внутри HTML-элемента-контейнера. Добавьте контейнер и задайте ему идентификатор, например *"root"*: + +~~~html title="index.html" +
+~~~ + +## Инициализация Pivot {#initialize-pivot} + +Конструктор `pivot.Pivot` принимает два параметра: + +- идентификатор HTML-контейнера +- объект с параметрами конфигурации + +Следующий фрагмент кода создаёт экземпляр Pivot в контейнере *"root"* с начальными полями, данными и структурой: + +~~~jsx +// создание Pivot +const table = new pivot.Pivot("#root", { + // параметры конфигурации + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +Конструктор возвращает экземпляр Pivot. Вызывайте методы API на возвращённом экземпляре: + +- [`getTable`](api/methods/gettable-method.md) — получить доступ к экземпляру виджета Table +- [`setConfig`](api/methods/setconfig-method.md) — обновить текущую конфигурацию Pivot +- [`setLocale`](api/methods/setlocale-method.md) — применить новую локаль к Pivot +- [`showConfigPanel`](api/methods/showconfigpanel-method.md) — показать или скрыть панель конфигурации + +## Параметры конфигурации {#configuration-properties} + +Конструктор Pivot принимает объект с параметрами конфигурации, управляющими данными, компоновкой и поведением компонента. + +:::info +Полный список параметров конфигурации Pivot см. в разделе [Обзор параметров](api/overview/properties-overview.md). +::: + +## Пример {#example} + +Фрагмент ниже инициализирует Pivot с начальными данными: + + diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md new file mode 100644 index 0000000..6e115fe --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md @@ -0,0 +1,325 @@ +--- +sidebar_label: Интеграция с Angular +title: Интеграция с Angular +description: Вы можете узнать об интеграции с Angular в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Интеграция с Angular {#integration-with-angular} + +:::tip +Предполагается знакомство с основными концепциями и паттернами **Angular**. Для повторения см. [**документацию Angular**](https://v17.angular.io/docs). +::: + +DHTMLX Pivot интегрируется с **Angular** как обычный компонент. Для полного рабочего примера см. [**демо Angular Pivot на GitHub**](https://github.com/DHTMLX/angular-pivot-demo). + +## Создание проекта {#create-a-project} + +:::info +Перед началом установите [**Angular CLI**](https://v1.angular.io/cli) и [**Node.js**](https://nodejs.org/en/). +::: + +Следующая команда создаёт новый Angular-проект с именем *my-angular-pivot-app*: + +~~~bash +ng new my-angular-pivot-app +~~~ + +:::note +При запросе Angular CLI отключите Server-Side Rendering (SSR) и Static Site Generation (SSG/Prerendering) — данное руководство предполагает клиентский рендеринг. +::: + +Команда установит все необходимые инструменты. Дополнительные команды не требуются. + +### Установка зависимостей {#install-dependencies} + +Перейдите в директорию нового проекта: + +~~~bash +cd my-angular-pivot-app +~~~ + +Установите зависимости и запустите сервер разработки с помощью менеджера пакетов [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # или: yarn dev +~~~ + +Приложение должно запуститься на локальном порту (например, `http://localhost:3000`). + +## Создание Pivot {#create-pivot} + +Добавьте пакет Pivot в проект, затем оберните Pivot в Angular-компонент. + +### Шаг 1. Установка пакета {#step-1-install-the-package} + +Загрузите [**ознакомительный пакет Pivot**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) и следуйте инструкциям в README. Ознакомительный пакет Pivot действителен в течение 30 дней. + +### Шаг 2. Создание компонента {#step-2-create-the-component} + +Создайте Angular-компонент, который монтирует Pivot. Добавьте папку *pivot* в *src/app/* и создайте файл *src/app/pivot/pivot.component.ts*. Затем выполните следующие шаги: + +#### Импорт исходных файлов {#import-source-files} + +Откройте *src/app/pivot/pivot.component.ts* и импортируйте пакет Pivot. Путь импорта зависит от редакции пакета: + +- **PRO-версия** (установлена из локальной папки): + +~~~jsx +import { Pivot } from 'dhx-pivot-package'; +~~~ + +- **Ознакомительная версия**: + +~~~jsx +import { Pivot } from '@dhx/trial-pivot'; +~~~ + +В этом руководстве используется ознакомительная версия Pivot. + +#### Настройка контейнера и монтирование Pivot {#set-up-the-container-and-mount-pivot} + +Чтобы отобразить Pivot на странице, определите элемент-контейнер в шаблоне компонента, затем инициализируйте Pivot в хуке `ngOnInit` с помощью конструктора. Уничтожьте Pivot в хуке `ngOnDestroy`. + +Следующий фрагмент кода определяет минимальный Angular-компонент Pivot: + +~~~jsx {1,8,12-13,18-19} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation } from '@angular/core'; + +@Component({ + encapsulation: ViewEncapsulation.None, + selector: "pivot", // имя шаблона, используемое в файле "app.component.ts" как + styleUrls: ["./pivot.component.css"], // подключение CSS-файла + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + // ссылка на контейнер для Pivot + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + // инициализация компонента Pivot + this._table = new Pivot(this.pivot_container.nativeElement, {}); + } + + ngOnDestroy(): void { + this._table.destructor(); // уничтожение Pivot при размонтировании + } +} +~~~ + +#### Добавление стилей {#add-styles} + +Чтобы Pivot отображался корректно, создайте файл *src/app/pivot/pivot.component.css* со стилями для страницы и контейнера Pivot: + +~~~css title="pivot.component.css" +/* импорт стилей Pivot */ +@import "@dhx/trial-pivot/dist/pivot.css"; + +/* стили для начальной страницы */ +html, +body { + margin: 0; + padding: 0; + height: 100%; +} + +/* стили для контейнера Pivot */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### Загрузка данных {#load-data} + +Чтобы передать данные в Pivot, подготовьте набор данных. Создайте файл *src/app/pivot/data.ts* и экспортируйте данные и метаданные полей: + +~~~jsx title="data.ts" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // другие элементы данных + ]; + + const fields: any = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // другие поля + ]; + + return { dataset, fields }; +}; +~~~ + +Откройте *src/app/pivot/pivot.component.ts*, импортируйте `getData` и примените набор данных в `ngOnInit()`: + +~~~jsx {2,18,20-21} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { getData } from "./data"; // импорт данных +import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation } from '@angular/core'; + +@Component({ + encapsulation: ViewEncapsulation.None, + selector: "pivot", + styleUrls: ["./pivot.component.css"], + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + const { dataset, fields } = getData(); // извлечение данных и метаданных полей + this._table = new Pivot(this.pivot_container.nativeElement, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // другие значения + ] + }, + // другие свойства конфигурации + }); + } + + ngOnDestroy(): void { + this._table.destructor(); + } +} +~~~ + +Компонент готов к использованию. При монтировании Pivot отрисовывается с переданными данными. Полный список свойств конфигурации см. в [документации API Pivot](api/overview/properties-overview.md). + +#### Обработка событий {#handle-events} + +Действия пользователя в Pivot генерируют события, на которые можно подписаться. Полный список событий см. в [обзоре событий](api/overview/events-overview.md). + +Следующий фрагмент кода расширяет `ngOnInit` слушателем события `open-filter`, который выводит в консоль идентификатор поля при открытии фильтра пользователем: + +~~~jsx {18-20} title="pivot.component.ts" +// ... +ngOnInit() { + const { dataset, fields } = getData(); + this._table = new Pivot(this.pivot_container.nativeElement, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // другие значения + ] + } + }); + + this._table.api.on("open-filter", (ev) => { + console.log("The field id for which the filter is activated:", ev.id); + }); +} + +ngOnDestroy(): void { + this._table.destructor(); +} +~~~ + +### Шаг 3. Добавление Pivot в приложение {#step-3-add-pivot-to-the-app} + +Чтобы встроить `PivotComponent` в приложение, откройте *src/app/app.component.ts* и замените код по умолчанию следующим: + +~~~jsx {5} title="app.component.ts" +import { Component } from "@angular/core"; + +@Component({ + selector: "app-root", + template: `` // шаблон, созданный в файле "pivot.component.ts" +}) +export class AppComponent { + name = ""; +} +~~~ + +Затем создайте файл *src/app/app.module.ts* и зарегистрируйте `PivotComponent`: + +~~~jsx {4-5,8} title="app.module.ts" +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; + +import { AppComponent } from "./app.component"; +import { PivotComponent } from "./pivot/pivot.component"; + +@NgModule({ + declarations: [AppComponent, PivotComponent], + imports: [BrowserModule], + bootstrap: [AppComponent] +}) +export class AppModule {} +~~~ + +Наконец, откройте *src/main.ts* и замените его содержимое следующим кодом начальной загрузки: + +~~~jsx title="main.ts" +import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; +import { AppModule } from "./app/app.module"; +platformBrowserDynamic() + .bootstrapModule(AppModule) + .catch((err) => console.error(err)); +~~~ + +Запустите приложение, чтобы увидеть отрисовку данных в Pivot на странице. + +![Инициализация Pivot](../assets/trial_pivot.png) + +Pivot теперь интегрирован с Angular. Настройте конфигурацию в соответствии с требованиями проекта. Итоговый пример см. в [**angular-pivot-demo на GitHub**](https://github.com/DHTMLX/angular-pivot-demo). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-react.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-react.md new file mode 100644 index 0000000..a5f90a1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-react.md @@ -0,0 +1,289 @@ +--- +sidebar_label: Интеграция с React +title: Интеграция с React +description: Вы можете узнать об интеграции с React в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Интеграция с React {#integration-with-react} + +:::tip +Предполагается знакомство с базовыми концепциями и паттернами [**React**](https://react.dev). Для повторения см. [**документацию React**](https://react.dev/learn). +::: + +DHTMLX Pivot интегрируется с **React** как обычный компонент. Для полного рабочего примера см. [**демо React Pivot на GitHub**](https://github.com/DHTMLX/react-pivot-demo). + +## Создание проекта {#create-a-project} + +:::info +Перед началом работы установите [**Node.js**](https://nodejs.org/en/). [**Vite**](https://vite.dev/) опционален. +::: + +Создайте базовый проект **React** (или проект на основе Vite) с именем *my-react-pivot-app*. + +Следующая команда создаёт проект Create React App: + +~~~bash +npx create-react-app my-react-pivot-app +~~~ + +### Установка зависимостей {#install-dependencies} + +Перейдите в директорию нового проекта: + +~~~bash +cd my-react-pivot-app +~~~ + +Установите зависимости и запустите dev-сервер с помощью вашего пакетного менеджера: + +- с [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # или: yarn dev +~~~ + +- с [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +Приложение должно запуститься на локальном порту (например, `http://localhost:3000`). + +## Создание Pivot {#create-pivot} + +Добавьте пакет Pivot в проект, затем оберните Pivot в React-компонент. + +### Шаг 1. Установка пакета {#step-1-install-the-package} + +Загрузите [**ознакомительный пакет Pivot**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) и следуйте инструкциям в README. Ознакомительный пакет Pivot действителен в течение 30 дней. + +### Шаг 2. Создание компонента {#step-2-create-the-component} + +Создайте React-компонент, который монтирует Pivot. Добавьте новый файл *src/Pivot.jsx*. + +#### Импорт исходных файлов {#import-source-files} + +Откройте *src/Pivot.jsx* и импортируйте исходные файлы Pivot. Пути импорта зависят от редакции пакета: + +- **PRO-версия** (установлена из локальной папки): + +~~~jsx title="Pivot.jsx" +import { Pivot } from 'dhx-pivot-package'; +import 'dhx-pivot-package/dist/pivot.css'; +~~~ + +Если пакет поставляется с минифицированными ресурсами, импортируйте *pivot.min.css* вместо *pivot.css*. + +- **Ознакомительная версия**: + +~~~jsx title="Pivot.jsx" +import { Pivot } from '@dhx/trial-pivot'; +import "@dhx/trial-pivot/dist/pivot.css"; +~~~ + +В этом руководстве используется ознакомительная версия Pivot. + +#### Настройка контейнера и монтирование Pivot {#set-up-the-container-and-mount-pivot} + +Для отображения Pivot на странице создайте контейнер `div`, затем инициализируйте Pivot в хуке `useEffect` с помощью конструктора. + +Следующий фрагмент кода определяет минимальный React-компонент Pivot: + +~~~jsx {2,6,9-10} title="Pivot.jsx" +import { useEffect, useRef } from "react"; +import { Pivot } from "@dhx/trial-pivot"; +import "@dhx/trial-pivot/dist/pivot.css"; // подключение стилей Pivot + +export default function PivotComponent(props) { + let container = useRef(); // реф контейнера для Pivot + + useEffect(() => { + // инициализация компонента Pivot + const table = new Pivot(container.current, {}); + + return () => { + table.destructor(); // уничтожение Pivot при размонтировании + }; + }, []); + + return
; +} +~~~ + +#### Добавление стилей {#add-styles} + +Для корректного отображения Pivot добавьте следующие стили в основной CSS-файл проекта: + +~~~css title="index.css" +/* стили для начальной страницы */ +html, +body, +#root { + height: 100%; + padding: 0; + margin: 0; +} + +/* стили для контейнера Pivot */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### Загрузка данных {#load-data} + +Для передачи данных в Pivot подготовьте набор данных. Создайте *src/data.js* и экспортируйте данные и метаданные полей: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // другие элементы данных + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // другие поля + ]; + + return { dataset, fields }; +}; +~~~ + +Откройте *src/App.js*, импортируйте данные и передайте их в компонент `` как пропсы: + +~~~jsx {2,5-6} title="App.js" +import Pivot from "./Pivot"; +import { getData } from "./data"; + +function App() { + const { fields, dataset } = getData(); + return ; +} + +export default App; +~~~ + +Откройте *src/Pivot.jsx*, деструктурируйте пропсы и примените их к объекту конфигурации Pivot: + +~~~jsx {5,10-11} title="Pivot.jsx" +import { useEffect, useRef } from "react"; +import { Pivot } from "@dhx/trial-pivot"; +import "@dhx/trial-pivot/dist/pivot.css"; + +export default function PivotComponent({ fields, dataset }) { + let container = useRef(); + + useEffect(() => { + const table = new Pivot(container.current, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // другие значения + ] + }, + // другие свойства конфигурации + }); + + return () => { + table.destructor(); + } + }, []); + + return
; +} +~~~ + +Компонент готов к использованию. При монтировании Pivot отображает переданные данные. Полный список свойств конфигурации см. в [документации API Pivot](api/overview/properties-overview.md). + +#### Обработка событий {#handle-events} + +Действия пользователя в Pivot генерируют события, на которые можно подписаться. Полный список событий см. в [обзоре событий](api/overview/events-overview.md). + +Следующий фрагмент кода расширяет `useEffect` обработчиком события `open-filter`, который записывает в лог идентификатор поля при открытии фильтра пользователем: + +~~~jsx {19-21} title="Pivot.jsx" +// ... +useEffect(() => { + const table = new Pivot(container.current, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // другие значения + ] + }, + // другие свойства конфигурации + }); + + table.api.on("open-filter", (ev) => { + console.log("The field id for which the filter is activated:", ev.id); + }); + + return () => { + table.destructor(); + } +}, []); +// ... +~~~ + +Запустите приложение, чтобы увидеть, как Pivot отображает данные на странице. + +![Инициализация Pivot](../assets/trial_pivot.png) + +Pivot теперь интегрирован с React. Настройте конфигурацию под требования проекта. Готовый пример см. в [**react-pivot-demo на GitHub**](https://github.com/DHTMLX/react-pivot-demo). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md new file mode 100644 index 0000000..bef499b --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md @@ -0,0 +1,302 @@ +--- +sidebar_label: Интеграция со Svelte +title: Интеграция со Svelte +description: Вы можете узнать об интеграции со Svelte в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства разработчика и справочник API, ознакомьтесь с примерами кода и живыми демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Интеграция со Svelte {#integration-with-svelte} + +:::tip +Предполагается знакомство с основными концепциями и паттернами **Svelte**. Для повторения см. [**документацию Svelte**](https://svelte.dev/). +::: + +DHTMLX Pivot интегрируется со **Svelte** как обычный компонент. Для полного рабочего примера см. [**демо Svelte Pivot на GitHub**](https://github.com/DHTMLX/svelte-pivot-demo). + +## Создание проекта {#create-a-project} + +:::info +Перед началом установите [**Node.js**](https://nodejs.org/en/). [**Vite**](https://vite.dev/) — опционально. +::: + +Следующая команда запускает инструмент создания проекта Vite и позволяет выбрать шаблон Svelte: + +~~~bash +npm create vite@latest +~~~ + +Назовите проект *my-svelte-pivot-app*. + +### Установка зависимостей {#install-dependencies} + +Перейдите в директорию нового проекта: + +~~~bash +cd my-svelte-pivot-app +~~~ + +Установите зависимости и запустите сервер разработки с помощью менеджера пакетов: + +- с [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # или: yarn dev +~~~ + +- с [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +Приложение должно запуститься на локальном порту (например, `http://localhost:3000`). + +## Создание Pivot {#create-pivot} + +Добавьте пакет Pivot в проект, затем оберните Pivot в компонент Svelte. + +### Шаг 1. Установка пакета {#step-1-install-the-package} + +Загрузите [**ознакомительный пакет Pivot**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) и следуйте инструкциям в README. Ознакомительный пакет Pivot действителен в течение 30 дней. + +### Шаг 2. Создание компонента {#step-2-create-the-component} + +Создайте компонент Svelte, который монтирует Pivot. Добавьте новый файл *src/Pivot.svelte*. + +#### Импорт исходных файлов {#import-source-files} + +Откройте *src/Pivot.svelte* и импортируйте исходные файлы Pivot. Пути импорта зависят от редакции пакета: + +- **PRO-версия** (установлена из локальной папки): + +~~~html title="Pivot.svelte" + +~~~ + +Если пакет поставляется с минифицированными ресурсами, импортируйте *pivot.min.css* вместо *pivot.css*. + +- **Ознакомительная версия**: + +~~~html title="Pivot.svelte" + +~~~ + +В этом руководстве используется ознакомительная версия Pivot. + +#### Настройка контейнера и монтирование Pivot {#set-up-the-container-and-mount-pivot} + +Чтобы отобразить Pivot на странице, добавьте контейнер `div`, затем инициализируйте Pivot в хуке жизненного цикла `onMount` с помощью конструктора. Уничтожьте Pivot в хуке `onDestroy`. + +Следующий фрагмент кода определяет минимальный компонент Svelte для Pivot: + +~~~html {3,6,10-11,19} title="Pivot.svelte" + + +
+~~~ + +#### Добавление стилей {#add-styles} + +Чтобы Pivot отображался корректно, добавьте следующие стили в основной CSS-файл проекта: + +~~~css title="main.css" +/* стили для начальной страницы */ +html, +body, +#app { /* используйте корневой контейнер #app */ + height: 100%; + padding: 0; + margin: 0; +} + +/* стили для контейнера Pivot */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### Загрузка данных {#load-data} + +Чтобы передать данные в Pivot, подготовьте набор данных. Создайте *src/data.js* и экспортируйте данные и метаданные полей: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // другие элементы данных + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // другие поля + ]; + + return { dataset, fields }; +}; +~~~ + +Откройте *src/App.svelte*, импортируйте данные и передайте их новому компоненту `` как пропсы: + +~~~html {3,5,8} title="App.svelte" + + + +~~~ + +Откройте *src/Pivot.svelte*, объявите входящие пропсы с помощью `export let` и примените их к объекту конфигурации Pivot: + +~~~html {6-7,14-15} title="Pivot.svelte" + + +
+~~~ + +Компонент готов к использованию. При монтировании Pivot отображает переданные данные. Полный список свойств конфигурации см. в [документации API Pivot](api/overview/properties-overview.md). + +#### Обработка событий {#handle-events} + +Действия пользователя в Pivot вызывают события, на которые можно подписаться. Полный список событий см. в [обзоре событий](api/overview/events-overview.md). + +Следующий фрагмент кода расширяет `onMount` обработчиком события `open-filter`, который записывает в лог идентификатор поля при открытии пользователем фильтра: + +~~~html {22-24} title="Pivot.svelte" + + +// ... +~~~ + +Запустите приложение, чтобы увидеть, как Pivot отображает данные на странице. + +![Инициализация Pivot](../assets/trial_pivot.png) + +Pivot теперь интегрирован со Svelte. Настройте конфигурацию в соответствии с требованиями проекта. Финальный пример см. на [**svelte-pivot-demo на GitHub**](https://github.com/DHTMLX/svelte-pivot-demo). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md new file mode 100644 index 0000000..ec18bac --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md @@ -0,0 +1,312 @@ +--- +sidebar_label: Интеграция с Vue +title: Интеграция с Vue +description: Узнайте об интеграции с Vue в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную пробную версию DHTMLX Pivot. +--- + +# Интеграция с Vue {#integration-with-vue} + +:::tip +Предполагается знакомство с базовыми концепциями и паттернами [**Vue**](https://vuejs.org/). Для повторения см. [**документацию Vue 3**](https://vuejs.org/guide/introduction.html#getting-started). +::: + +DHTMLX Pivot интегрируется с **Vue** как обычный компонент. Полный рабочий пример см. в [**демо Vue Pivot на GitHub**](https://github.com/DHTMLX/vue-pivot-demo). + +## Создание проекта {#create-a-project} + +:::info +Перед началом работы установите [**Node.js**](https://nodejs.org/en/). +::: + +Следующая команда запускает официальный инструмент создания проектов **Vue**: + +~~~bash +npm create vue@latest +~~~ + +Команда устанавливает и запускает `create-vue`. Подробнее см. [Быстрый старт Vue.js](https://vuejs.org/guide/quick-start.html#creating-a-vue-application). + +Назовите проект *my-vue-pivot-app*. + +### Установка зависимостей {#install-dependencies} + +Перейдите в директорию нового проекта: + +~~~bash +cd my-vue-pivot-app +~~~ + +Установите зависимости и запустите сервер разработки с помощью вашего пакетного менеджера: + +- с [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # или: yarn dev +~~~ + +- с [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +Приложение должно запуститься на локальном порту (например, `http://localhost:3000`). + +## Создание Pivot {#create-pivot} + +Добавьте пакет Pivot в проект, затем оберните Pivot в компонент Vue. + +### Шаг 1. Установка пакета {#step-1-install-the-package} + +Скачайте [**пробный пакет Pivot**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) и следуйте инструкциям в README. Пробный пакет Pivot действителен в течение 30 дней. + +### Шаг 2. Создание компонента {#step-2-create-the-component} + +Создайте компонент Vue, который монтирует Pivot. Добавьте новый файл *src/components/Pivot.vue*. + +#### Импорт исходных файлов {#import-source-files} + +Откройте *src/components/Pivot.vue* и импортируйте исходные файлы Pivot. Пути импорта зависят от редакции пакета: + +- **PRO версия** (установленная из локальной папки): + +~~~html title="Pivot.vue" + +~~~ + +Если пакет поставляется с минифицированными ресурсами, импортируйте *pivot.min.css* вместо *pivot.css*. + +- **Пробная версия**: + +~~~html title="Pivot.vue" + +~~~ + +В этом руководстве используется пробная версия Pivot. + +#### Настройка контейнера и монтирование Pivot {#set-up-the-container-and-mount-pivot} + +Чтобы отобразить Pivot на странице, добавьте контейнер `div`, затем инициализируйте Pivot в хуке `mounted` с помощью конструктора. Уничтожьте Pivot в хуке `unmounted`. + +Следующий фрагмент кода определяет минимальный компонент Pivot для Vue: + +~~~html {2,7-8,18} title="Pivot.vue" + + + +~~~ + +#### Добавление стилей {#add-styles} + +Для корректного отображения Pivot добавьте следующие стили в главный CSS-файл проекта: + +~~~css title="style.css" +/* стили для начальной страницы */ +html, +body, +#app { /* используем корневой контейнер #app */ + height: 100%; + padding: 0; + margin: 0; +} + +/* стили для контейнера Pivot */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### Загрузка данных {#load-data} + +Чтобы передать данные в Pivot, подготовьте набор данных. Создайте *src/data.js* и экспортируйте данные и метаданные полей: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // другие элементы данных + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // другие поля + ]; + + return { dataset, fields }; +}; +~~~ + +Откройте *src/App.vue*, импортируйте данные и передайте их через опцию `data()`. Затем передайте значения новому компоненту `` в качестве пропсов: + +~~~html {3,7-13,18} title="App.vue" + + + +~~~ + +Откройте *src/components/Pivot.vue*, объявите входящие пропсы и примените их к объекту конфигурации Pivot: + +~~~html {6,10-11} title="Pivot.vue" + + + +~~~ + +Компонент готов к использованию. При монтировании Pivot отображает данные. Полный список свойств конфигурации см. в [документации API Pivot](api/overview/properties-overview.md). + +#### Обработка событий {#handle-events} + +Действия пользователя в Pivot генерируют события, на которые можно подписаться. Полный список событий см. в [Обзоре событий](api/overview/events-overview.md). + +Следующий фрагмент кода расширяет `mounted` обработчиком события `open-filter`, который выводит в консоль идентификатор поля при открытии фильтра пользователем: + +~~~html {22-24} title="Pivot.vue" + + +// ... +~~~ + +Запустите приложение, чтобы увидеть, как Pivot отображает данные на странице. + +![Инициализация Pivot](../assets/trial_pivot.png) + +Pivot теперь интегрирован с Vue. Настройте конфигурацию в соответствии с требованиями проекта. Финальный пример см. в [**vue-pivot-demo на GitHub**](https://github.com/DHTMLX/vue-pivot-demo). diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/loading-data.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/loading-data.md new file mode 100644 index 0000000..68566ef --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/loading-data.md @@ -0,0 +1,279 @@ +--- +sidebar_label: Загрузка данных +title: Загрузка данных +description: Вы можете узнать, как загружать данные, в документации библиотеки DHTMLX JavaScript Pivot. Изучайте руководства для разработчиков и справочник API, пробуйте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Загрузка данных + +Pivot принимает данные в формате JSON через свойство [`data`](api/config/data-property.md). Также Pivot принимает данные в формате CSV после их конвертации в JSON. + +## Подготовка данных для загрузки {#prepare-data-for-loading} + +Свойство [`data`](api/config/data-property.md) принимает массив объектов, где каждый объект представляет одну строку данных. Ключи каждого объекта определяют измерения и значения, используемые в таблице Pivot. + +Следующий фрагмент кода определяет пример массива `data`: + +~~~jsx +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + { + name: "Argentina", + year: 2017, + continent: "South America", + form: "Republic", + gdp: 212.507, + oil: 1.732, + balance: 7.167, + when: new Date("1/15/2017") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 260.071, + oil: 2.845, + balance: 6.728, + when: new Date("6/16/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 324.405, + oil: 4.333, + balance: 5.99, + when: new Date("2/20/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 305.763, + oil: 2.626, + balance: 7.544, + when: new Date("8/17/2014") + }, + // другие данные +]; +~~~ + +:::info +Информацию об определении полей и структуры Pivot см. в разделе [Работа с данными](guides/working-with-data.md). +::: + +## Загрузка данных из файла {#load-data-from-a-file} + +Pivot загружает данные JSON из внешнего файла после инициализации. Подготовьте исходный файл с данными, полями и конфигурацией. + +Следующий фрагмент кода определяет `data`, `fields` и метод доступа `getData()` в отдельном файле: + +~~~jsx +function getData() { + return { + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"], + } + } + }, + fields + }; +} +const fields = [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } +]; + +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + // другие данные +]; +~~~ + +Добавьте путь к исходному файлу данных в разметку страницы: + +~~~html title="index.html" + + + + +~~~ + +Следующий фрагмент кода создаёт Pivot и загружает данные из подготовленного файла: + +~~~jsx +const { data, config, fields } = getData(); +const table = new pivot.Pivot("#root", { data, config, fields }); +~~~ + +## Загрузка данных с сервера {#load-data-from-a-server} + +Чтобы загрузить данные с серверного эндпоинта, отправьте запрос с помощью нативного метода `fetch` (или любого аналога), а затем передайте ответ в [`setConfig`](api/methods/setconfig-method.md), который обновляет конфигурацию Pivot и сохраняет ранее установленные параметры. + +Следующий фрагмент кода инициализирует Pivot с пустыми данными, загружает данные и поля с сервера, а затем применяет их с помощью `setConfig`: + +~~~jsx +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +Promise.all([ + fetch(server + "/data").then((res) => res.json()), + fetch(server + "/fields").then((res) => res.json()) +]).then(([data, fields]) => { + table.setConfig({ data, fields }); +}); +~~~ + +Дополнительную информацию см. в следующем разделе: [Работа с сервером](/guides/working-with-server) + +## Загрузка данных CSV {#load-csv-data} + +Pivot принимает данные CSV после их конвертации в JSON с помощью внешней библиотеки JS для парсинга. Сконвертированные данные ведут себя так же, как и нативный JSON. + +В примере ниже используется внешняя библиотека [PapaParse](https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js) для загрузки и конвертации данных по нажатию кнопки. Вспомогательная функция `convert()` принимает следующие параметры: + +- `data` — строка с данными CSV +- `headers` — массив названий полей CSV +- `meta` — объект, сопоставляющий названия полей с типами данных + +Следующий фрагмент кода создаёт Pivot, определяет вспомогательную функцию `convert()` и применяет спарсенные данные CSV через [`setConfig`](api/methods/setconfig-method.md) по нажатию кнопки: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +function convert(data, headers, meta) { + const header = headers.join(",") + "\n"; + const processedData = header + data; + + return Papa.parse(processedData, { + header: true, + dynamicTyping: true, + transform: (v, f) => { + return meta && meta[f] === "date" ? new Date(v) : v; + } + }); +} + +function fromCSV() { + const fields = [ + { id: "name", label: "Name", type: "text" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "gdp", label: "GDP", type: "number" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" }, + { id: "year", label: "Year", type: "number" }, + { id: "when", label: "When", type: "date" } + ]; + + const config = { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }; + + const headers = [ + "name", + "year", + "continent", + "form", + "gdp", + "oil", + "balance", + "when" + ]; + + // явно помечаем поля с датами для корректной конвертации + const meta = { when: "date" }; + + const dataURL = "https://some-backend-url"; + fetch(dataURL) + .then(response => response.text()) + .then(text => convert(text, headers, meta)) + .then(data => { + table.setConfig({ + data: data.data, + fields, + config + }); + }); +} + +const importButton = document.createElement("button"); +importButton.addEventListener("click", fromCSV); +importButton.textContent = "Import"; + +document.body.appendChild(importButton); +~~~ + +## Пример {#example} + +Фрагмент ниже загружает данные JSON и CSV: + + + +**Связанные примеры**: +- [Pivot 2. Формат даты](https://snippet.dhtmlx.com/shn1l794) +- [Pivot 2. Разные наборы данных](https://snippet.dhtmlx.com/6xtqge4i) +- [Pivot 2. Большой набор данных](https://snippet.dhtmlx.com/e6qwqrys) + +**Связанные статьи**: [Форматирование дат](guides/localization.md#date-formatting) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/localization.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/localization.md new file mode 100644 index 0000000..cafbfd7 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/localization.md @@ -0,0 +1,293 @@ +--- +sidebar_label: Локализация +title: Локализация +description: Вы можете узнать о локализации в документации библиотеки DHTMLX JavaScript Pivot. Изучите руководства разработчика и справочник API, попробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Локализация + +Pivot позволяет локализовать каждую метку интерфейса. Создайте новую локаль или измените встроенную, затем примените локаль к Pivot через свойство [`locale`](api/config/locale-property.md) или метод [`setLocale`](api/methods/setlocale-method.md). + +## Локаль по умолчанию {#default-locale} + +По умолчанию Pivot использует английскую локаль. Следующий фрагмент кода показывает структуру встроенной локали `en`: + +~~~jsx +const en = { + // pivot + pivot: { + sum: "Sum", + min: "Min", + max: "Max", + count: "Count", + counta: "CountA", + countunique: "CountUnique", + average: "Average", + median: "Median", + product: "Product", + stdev: "StDev", + stdevp: "StDevP", + var: "Var", + varp: "VarP", + "Raw date": "Raw date", + "Raw number": "Raw number", + "Raw text": "Raw text", + Year: "Year", + Month: "Month", + Day: "Day", + Hour: "Hour", + Minute: "Minute", + Total: "Total", + Values: "Values", + Rows: "Rows", + Columns: "Columns", + "Click on the plus icon(s) to add data": + "Click on the plus icon(s) to add data", + 'Click on "Show settings" to see the available configuration options': + 'Click on "Show settings" to see the available configuration options', + "Show settings": "Show settings", + "Hide settings": "Hide settings" + }, + + // query + query: { + "Add filter": "Add filter", + "Add Filter": "Add Filter", + "Add Group": "Add Group", + Edit: "Edit", + Delete: "Delete", + + "Select all": "Select all", + "Unselect all": "Unselect all", + + Cancel: "Cancel", + Apply: "Apply", + + and: "and", + or: "or", + in: "in", + + equal: "equal", + "not equal": "not equal", + contains: "contains", + "not contains": "not contains", + "begins with": "begins with", + "not begins with": "not begins with", + "ends with": "ends with", + "not ends with": "not ends with", + + greater: "greater", + "greater or equal": "greater or equal", + less: "less", + "less or equal": "less or equal", + between: "between", + "not between": "not between" + }, + + // calendar + calendar: { + monthFull: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ], + monthShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ], + + dayFull: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ], + + dayShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + hours: "Hours", + minutes: "Minutes", + done: "Done", + clear: "Clear", + today: "Today", + am: ["am", "AM"], + pm: ["pm", "PM"], + + weekStart: 7, + clockFormat: 24, + }, + + // core + core: { + ok: "OK", + cancel: "Cancel", + select: "Select", + "No data": "No data" + }, + + // formats + formats: { + dateFormat: "%d.%m.%Y", + timeFormat: "%H:%i" + }, + + lang: "en-US", +}; +~~~ + +## Применение локали {#apply-a-locale} + +Pivot предоставляет три встроенные локали через объект `pivot.locales`: `en`, `de` и `cn`. Передайте встроенную локаль в свойство [`locale`](api/config/locale-property.md) при инициализации. + +Следующий фрагмент кода инициализирует Pivot с немецкой локалью: + +~~~jsx +new pivot.Pivot("#root", { + // other properties + locale: pivot.locales.de, +}); +~~~ + +Чтобы применить пользовательскую локаль: + +- создайте объект локали (или измените встроенный) и задайте переводы для всех текстовых меток (на любом языке) +- примените локаль к Pivot через свойство [`locale`](api/config/locale-property.md) или метод [`setLocale`](api/methods/setlocale-method.md) + +Следующий фрагмент кода создаёт Pivot, а затем применяет пользовательскую корейскую локаль во время выполнения с помощью `setLocale`: + +~~~jsx +// create Pivot +const widget = new pivot.Pivot("#root", { + data, + // other configuration properties +}); + +const ko = { /* object with locale */ }; +widget.setLocale(ko); +~~~ + +:::tip +Вызовите [`setLocale`](api/methods/setlocale-method.md) без аргументов (или с `null`), чтобы сбросить Pivot к локали по умолчанию (английской). +::: + +## Форматирование дат {#date-formatting} + +Pivot принимает даты в виде объектов `Date`. Перед передачей данных в Pivot преобразуйте строковые значения в `Date`. Значение `dateFormat` по умолчанию — `"%d.%m.%Y"`, оно берётся из текущей локали. + +Чтобы изменить формат для всех полей с датами, задайте новое значение для `dateFormat` в объекте `formats` свойства [`locale`](api/config/locale-property.md). + +Следующий фрагмент кода преобразует строковые даты в объекты `Date`, затем инициализирует Pivot с пользовательским `dateFormat` и обновляет формат во время выполнения через `setConfig`: + +~~~jsx {17} +function setFormat(value) { + table.setConfig({ locale: { formats: { dateFormat: value } } }); +} + +// convert date strings to Date objects +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + locale: { formats: { dateFormat: "%d %M %Y %H:%i" } }, + fields, + data: dataset, + config: { + rows: ["state"], + columns: ["product_line", "product_type"], + values: [ + { + field: "date", + method: "min" + }, + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + } + ] + } +}); +~~~ + +Чтобы задать пользовательский формат для конкретного поля, используйте параметр `format` свойства [`fields`](api/config/fields-property.md). См. раздел [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields). + +## Символы формата даты и времени {#date-and-time-format-characters} + +Pivot использует следующие символы для определения формата даты и времени: + +| Символ | Описание | Пример | +| :-------- | :------------------------------------------------------------ |:------------------------| +| %d | день в виде числа с ведущим нулём | от 01 до 31 | +| %j | день в виде числа | от 1 до 31 | +| %D | краткое название дня (аббревиатура) | Su Mo Tu Sat | +| %l | полное название дня | Sunday Monday Tuesday | +| %W | неделя в виде числа с ведущим нулём (понедельник — первый день недели) | от 01 до 52/53 | +| %m | месяц в виде числа с ведущим нулём | от 01 до 12 | +| %n | месяц в виде числа | от 1 до 12 | +| %M | краткое название месяца | Jan Feb Mar | +| %F | полное название месяца | January February March | +| %y | год в виде числа, 2 цифры | 24 | +| %Y | год в виде числа, 4 цифры | 2024 | +| %h | часы в 12-часовом формате с ведущим нулём | от 01 до 12 | +| %g | часы в 12-часовом формате | от 1 до 12 | +| %H | часы в 24-часовом формате с ведущим нулём | от 00 до 23 | +| %G | часы в 24-часовом формате | от 0 до 23 | +| %i | минуты с ведущим нулём | от 01 до 59 | +| %s | секунды с ведущим нулём | от 01 до 59 | +| %S | миллисекунды | 128 | +| %a | am или pm | am (время от полуночи до полудня) и pm (время от полудня до полуночи)| +| %A | AM или PM | AM (время от полуночи до полудня) и PM (время от полудня до полуночи)| +| %c | отображает дату и время в формате ISO 8601 | 2024-10-04T05:04:09 | + +Чтобы представить 20 сентября 2024 года в 16:47:08.128 как *2024-09-20 16:47:08.128*, используйте формат `"%Y-%m-%d %H:%i:%s.%S"`. + +## Форматирование чисел {#number-formatting} + +Pivot локализует все поля типа `number` на основе значения `lang` текущей локали. Виджет использует спецификацию [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). По умолчанию ограничивается до 3 знаков после запятой и применяется разделение групп для целой части. + +Чтобы отключить форматирование для конкретного числового поля или задать пользовательский формат, используйте параметр `format` свойства [`fields`](api/config/fields-property.md). Установите `format` в `false`, чтобы отключить форматирование, или передайте объект с настройками формата (см. раздел [Применение форматов к полям](guides/working-with-data.md#applying-formats-to-fields)). + +Следующий фрагмент кода отключает числовое форматирование для поля `year`: + +~~~jsx +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +## Пример {#example} + +Фрагмент ниже демонстрирует переключение между несколькими локалями: + + diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/stylization.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/stylization.md new file mode 100644 index 0000000..d2e7b47 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/stylization.md @@ -0,0 +1,266 @@ +--- +sidebar_label: Стилизация +title: Стилизация +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о стилизации компонента. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Стилизация {#styling} + +Pivot поставляется с темой оформления по умолчанию и предоставляет CSS-переменные и вспомогательные классы для кастомизации. Переопределите переменные на контейнере виджета (или любом родительском элементе), чтобы изменить цвета, рамки и другие визуальные свойства. + +## Стиль по умолчанию {#default-style} + +Тема по умолчанию для Pivot — **Material**. Следующий CSS-фрагмент показывает переменные, которые тема Material устанавливает на контейнере виджета: + +~~~css +.wx-material-theme { + --wx-theme-name: material; + --wx-pivot-primary-hover: #194e9e; + --wx-pivot-border-color: var(--wx-color-font-disabled); + --wx-pivot-field-hover: linear-gradient( + rgba(0, 0, 0, 0.1) 0%, + rgba(0, 0, 0, 0.1) 100% + ); +} +~~~ + +:::tip Примечание +В будущих версиях Pivot CSS-переменные могут быть переименованы. После обновления проверяйте имена переменных и обновляйте их в коде, чтобы избежать проблем с отображением. +::: + +## Встроенная тема {#built-in-theme} + +Pivot предоставляет одну встроенную тему: **Material**. Применить тему можно двумя способами: добавить класс темы к контейнеру виджета или подключить готовую таблицу стилей скина на странице. + +Следующий фрагмент кода применяет тему Material, добавляя класс `wx-material-theme` к контейнеру виджета: + +~~~html {} + +
+~~~ + +Следующий фрагмент кода подключает таблицу стилей скина Material напрямую: + +~~~html {} + +~~~ + +## Настройка встроенной темы {#customize-built-in-theme} + +Переопределите переменные темы Material на селекторе `.wx-material-theme`, чтобы изменить цвета, рамки и другие визуальные свойства. + +Пример ниже переопределяет переменные темы Material для отображения Pivot в тёмной цветовой схеме: + +~~~html + + +~~~ + +## Пользовательский стиль {#custom-style} + +Измените внешний вид Pivot, переопределив CSS-переменные на пользовательском классе, применённом к контейнеру виджета. + +Пример ниже применяет пользовательский стиль к Pivot через класс `.demo`: + +~~~html +
+ +~~~ + +## Стиль полосы прокрутки {#scroll-style} + +Примените пользовательский стиль к полосе прокрутки Pivot с помощью CSS-класса `.wx-styled-scroll`. Перед использованием проверьте совместимость с браузерами: [caniuse: CSS Scrollbar](https://caniuse.com/css-scrollbar). + +Следующий фрагмент кода включает стилизованную полосу прокрутки на контейнере виджета: + +~~~html {} title="index.html" + +
+~~~ + +## Стиль ячеек {#cell-style} + +Для стилизации ячеек тела или подвала таблицы используйте параметр `cellStyle` свойства [`tableShape`](api/config/tableshape-property.md). Для стилизации ячеек заголовка используйте параметр `cellStyle` свойства [`headerShape`](api/config/headershape-property.md). В обоих случаях функция `cellStyle` возвращает имя CSS-класса, который Pivot применяет к ячейке. + +Пример ниже применяет стили к ячейкам тела и заголовка: + +- ячейки тела получают класс на основе значений ячейки (например, `"Down"`, `"Up"`, `"Idle"` в поле `status`) и итоговых значений (больше 40 или меньше 5) +- ячейки заголовка получают класс на основе значения поля `streaming` — `status-down` для `"no"` и `status-up` для любого другого значения + +~~~jsx +const widget = new pivot.Pivot("#pivot", { + tableShape: { + totalColumn: true, + totalRow:true, + cellStyle: (field, value, area, method, isTotal) => { + if (field === "status" && area === "rows" && value) { + if (value === "Down") { + return "status-down"; + } else if (value === "Up") { + return "status-up"; + } else if (value === "Idle") { + return "status-idle"; + } + } + if(isTotal ==="column" && area == "values"){ + if(value > 40) + return "status-up"; + else if (value < 5) + return "status-down"; + } + } + }, + headerShape:{ + cellStyle:(field, value, area, method, isTotal) => { + if(field == "streaming") + return value ==="no"?"status-down":"status-up"; + } + }, + fields, + data: dataset, + config: { + rows: [ + "protocol", + "status", + ], + columns: [ + "streaming" + ], + values: [ + { + field: "id", + method: "count" + } + ] + } +}); +~~~ + +## Отметка значений в ячейках {#mark-values-in-cells} + +Используйте параметр `marks` свойства [`tableShape`](api/config/tableshape-property.md), чтобы применить CSS-класс к ячейкам, удовлетворяющим условию. Каждая запись в `marks` связывает имя CSS-класса (ключ) с правилом (значение). + +Правило — это либо предопределённая строка (`"max"` или `"min"`), либо пользовательская функция `(value, columnData, rowData) => boolean`. Когда функция возвращает `true`, Pivot добавляет CSS-класс к ячейке. + +Создайте CSS-классы в вашей таблице стилей перед применением `marks`. + +Пример ниже выделяет ячейки с минимальными и максимальными значениями, а также использует пользовательскую функцию для отметки нецелых значений больше 2: + +~~~jsx {18-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + marks: { + // встроенные метки (выделение min/max) + min_cell: "min", + max_cell: "max", + // пользовательская метка + g_avg: v => (v % 1 !== 0) && v > 2 + } + } +}); +~~~ + +Следующий фрагмент кода определяет CSS-классы, на которые ссылается объект `marks`: + +~~~html title="index.html" + +~~~ + +## Специфические CSS-классы {#specific-css-classes} + +Pivot включает несколько вспомогательных CSS-классов, которые можно переопределить для точного управления элементами таблицы. + +Pivot выравнивает числа в ячейках тела по правому краю с помощью встроенного CSS-класса `.wx-number`. Исключение составляет иерархическая колонка в режиме дерева (когда в [`tableShape`](api/config/tableshape-property.md) установлено `tree: true`). Чтобы сбросить выравнивание чисел по умолчанию, переопределите этот класс. + +Следующий фрагмент кода выравнивает числа в ячейках тела по левому краю: + +~~~html + +~~~ + +Для стилизации итоговых колонок переопределите CSS-класс `.wx-total`. + +Следующий фрагмент кода стилизует итоговые ячейки со светлым фоном и более жирным шрифтом: + +~~~html + +~~~ + +## Пример {#example} + +Фрагмент ниже применяет пользовательский стиль к Pivot: + + + +**Связанные примеры**: + +- [Pivot 2. Стилизация (пользовательский CSS) для итоговой колонки](https://snippet.dhtmlx.com/9lkdbzmm) +- [Pivot 2. Метки min/max и пользовательские метки для ячеек (условное форматирование)](https://snippet.dhtmlx.com/4cm4asbd) +- [Pivot 2. Чередование цвета строк (полосатые строки, зебра-стайп)](https://snippet.dhtmlx.com/0cm0uko2) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/typescript-support.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/typescript-support.md new file mode 100644 index 0000000..9ddfca1 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/typescript-support.md @@ -0,0 +1,17 @@ +--- +sidebar_label: Поддержка TypeScript +title: Поддержка TypeScript +description: Вы можете узнать об использовании TypeScript с библиотекой DHTMLX JavaScript Pivot в документации. Ознакомьтесь с руководствами разработчика и справочником API, попробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Поддержка TypeScript {#typescript-support} + +DHTMLX Pivot поставляется с определениями TypeScript начиная с версии v2.0. Определения готовы к использованию — дополнительная настройка не требуется. + +:::info +Попробуйте Pivot в [Snippet Tool](https://snippet.dhtmlx.com/y2buoahe). +::: + +## Преимущества TypeScript {#advantages-of-typescript} + +Проверка типов и автодополнение помогают выявлять ошибки на раннем этапе, а встроенные определения сообщают, какие именно типы данных ожидает API DHTMLX Pivot. diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/working-with-data.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/working-with-data.md new file mode 100644 index 0000000..1b12863 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/working-with-data.md @@ -0,0 +1,687 @@ +--- +sidebar_label: Работа с данными +title: Работа с данными +description: В документации библиотеки DHTMLX JavaScript Pivot вы найдёте информацию о работе с данными. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Работа с данными + +На этой странице описано, как агрегировать, форматировать, сортировать, фильтровать и предварительно обрабатывать данные в Pivot. Инструкции по загрузке и экспорту данных см. в разделах [Загрузка данных](guides/loading-data.md) и [Экспорт данных](guides/exporting-data.md). + +## Определение полей {#define-fields} + +Используйте свойство [`fields`](api/config/fields-property.md), чтобы объявить поля, которые Pivot может размещать в строках, столбцах и значениях. Каждый элемент массива `fields` описывает одно поле — его идентификатор, метку и тип данных. + +Следующий фрагмент кода инициализирует Pivot с пятью полями: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields: [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } + ], + data, + config: {...} +}); +~~~ + +## Применение форматов к полям {#applying-formats-to-fields} + +Pivot применяет формат по умолчанию к числовым полям и полям дат на основе текущей локали. Подробнее см. в разделах [Форматирование дат](guides/localization.md#date-formatting) и [Форматирование чисел](guides/localization.md#number-formatting). + +Чтобы переопределить формат по умолчанию для конкретного поля, задайте параметр `format` свойства [`fields`](api/config/fields-property.md). + +### Форматирование числовых полей {#format-numeric-fields} + +Используйте `prefix` и `suffix`, чтобы добавить текст вокруг числовых значений, и `maximumFractionDigits`, чтобы управлять точностью десятичных знаков. Например, чтобы отображать `12.345` как `"12.35 EUR"`, задайте суффикс `" EUR"` и `maximumFractionDigits` равным `2`: + +~~~js +const fields = [ + { id: "sales", type: "number", format: { suffix: " EUR", maximumFractionDigits: 2 } }, +]; +~~~ + +Форматирование по умолчанию ограничивает числовые поля тремя знаками после запятой и применяет разделение групп к целой части. Чтобы полностью отключить форматирование, задайте `format` значение `false`: + +~~~js +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +В примере ниже поля `marketing`, `profit` и `sales` помечены как денежные с префиксом `$` и фиксированными двумя десятичными знаками: + +~~~jsx +// инициализация Pivot с предопределённым набором данных и полями +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { field: "marketing", method: "sum" }, + // другие значения + + ], + }, + fields:[ + // пользовательский формат + { id: "marketing", label: "Marketing", type:"number", format:{ + prefix: "$", minimumFractionDigits: 2, maximumFractionDigits: 2 } + } + ] +}); +~~~ + +### Форматирование полей дат {#format-date-fields} + +Чтобы переопределить общий `dateFormat` локали для отдельного поля, задайте параметр `format` свойства [`fields`](api/config/fields-property.md) в виде строки формата даты. + +Следующий фрагмент кода задаёт `"%M %d, %Y"` в качестве формата для поля `date`: + +~~~jsx +const fields = [ + { id: "date", type: "date", format: "%M %d, %Y" }, +]; +~~~ + +В примере ниже строковые даты преобразуются в объекты `Date`, после чего Pivot инициализируется с форматом `"%d %M %Y %H:%i"` для поля `date`. Значения поля отображаются в виде меток, например `"24 April 2025 14:30"`. + +~~~jsx +// преобразование строковых дат в объекты Date +const dateFields = fields.filter(f => f.type === "date"); +dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v === "string") { + item[f.id] = new Date(v); + } + }); +}); + +// инициализация Pivot с полевым форматом даты +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state"], + columns: ["product_type"], + values: [ + { field: "date", method: "min" }, + { field: "profit", method: "sum" }, + { field: "sales", method: "sum" } + ] + }, + fields:[ + // пользовательский формат: День Месяц Год Часы:Минуты + { id: "date", label: "Date", type: "date", format: "%d %M %Y %H:%i" } + ] +}); +~~~ + +:::note +Для формата экспорта `xlsx` Pivot экспортирует поля дат и числовые поля как необработанные значения с форматом по умолчанию (или форматом, заданным через свойство [`fields`](api/config/fields-property.md)). Если для поля задан шаблон (см. свойство [`tableShape`](api/config/tableshape-property.md)), Pivot экспортирует отрисованное значение, полученное этим шаблоном. Если заданы и `template`, и `format`, шаблон имеет приоритет над форматом. +::: + +## Определение структуры Pivot {#define-pivot-structure} + +Используйте свойство [`config`](api/config/config-property.md), чтобы объявить, какие поля отображаются как строки, столбцы и агрегированные значения, а также как фильтруются данные. Свойство `config` не имеет предопределённых значений — вы должны задать его для отображения любых данных. Полный список параметров см. в справочнике [`config`](api/config/config-property.md). + +Следующий фрагмент кода помещает `continent` и `name` в строки, `year` — в столбцы, три агрегации — в значения и добавляет фильтр по `name`: + +~~~jsx {4-18} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }, + fields, + filters: { + name: { + contains: "B" + } + } +}); +~~~ + +## Сортировка данных {#sorting-data} + +Pivot поддерживает сортировку во всех трёх областях (значения, столбцы, строки) в процессе агрегации. В интерфейсе пользователи нажимают на заголовок столбца для сортировки. + +Чтобы задать сортировку по умолчанию, используйте параметр `sort` свойства [`fields`](api/config/fields-property.md). Параметр принимает `"asc"`, `"desc"` или пользовательскую функцию сравнения. + +В примере ниже над Pivot отображаются кликабельные метки полей, и при нажатии направление сортировки переключается: + +~~~jsx +const bar = document.getElementById("bar"); + +let sorted = ["studio", "genre"]; +setFields(); +bar.addEventListener('click', (e) => switchSort(e.target.id), false); + +function setFields(){ + let html = ""; + let sortedFields = fields.filter(f => (sorted.indexOf(f.id) != -1)); + + sortedFields.forEach((f) =>{ + const order = f.sort || "asc"; + html += `
+ ${f.label} +
`; + }); + bar.innerHTML = html; +} + +function switchSort(id){ + fields.forEach(f => { + if(f.id == id){ + f.sort = f.sort != "desc" ? "desc" : "asc"; + } + }); + // обновление полей Pivot + table.setConfig({ fields }); + // обновление иконок + setFields(bar, fields); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +Сортировка в интерфейсе включена по умолчанию. Чтобы отключить её, задайте параметр `sort` свойства [`columnShape`](api/config/columnshape-property.md) равным `false`. + +Следующий фрагмент кода отключает сортировку в интерфейсе: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +## Фильтрация данных {#filtering-data} + +Pivot поддерживает фильтры, привязанные к типам данных полей. Фильтры задаются через интерфейс Pivot после инициализации или декларативно через объект `filters` свойства [`config`](api/config/config-property.md). + +В интерфейсе фильтры отображаются в виде выпадающих списков для каждого поля. + +#### Типы фильтров {#filter-types} + +Pivot поддерживает следующие условия фильтрации по типам данных: + +- текстовые поля — `equal`, `notEqual`, `contains`, `notContains`, `beginsWith`, `notBeginsWith`, `endsWith`, `notEndsWith`, `includes` +- числовые поля — `equal`, `notEqual`, `greater`, `greaterOrEqual`, `less`, `lessOrEqual`, `contains`, `notContains`, `beginsWith`, `notBeginsWith`, `endsWith`, `notEndsWith` +- поля дат — `equal`, `notEqual`, `greater`, `greaterOrEqual`, `less`, `lessOrEqual`, `between`, `notBetween`, `includes` + +Правило `includes` ограничивает фильтр конкретным набором допустимых значений. + +#### Добавление фильтра {#add-a-filter} + +Чтобы объявить фильтр, добавьте объект `filters` в свойство [`config`](api/config/config-property.md), используя идентификатор поля в качестве ключа. Каждое значение — объект с условиями фильтрации. + +Следующий фрагмент кода применяет два фильтра — один по `genre` (значения, содержащие `"D"`, ограниченные значением `"Drama"`) и один по `title` (значения, содержащие `"A"`): + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // фильтр для другого поля ("title") + contains: "A" + } + } + } +}); +~~~ + +:::info +Чтобы фильтровать данные через API виджета Table, получите экземпляр Table с помощью метода [`getTable`](api/methods/gettable-method.md) и используйте событие [`filter-rows`](api/table/filter-rows.md). +::: + +## Ограничение загружаемых данных {#limiting-loaded-data} + +Чтобы предотвратить зависание компонента на очень больших наборах данных, ограничьте количество строк и столбцов в итоговом наборе с помощью свойства [`limits`](api/config/limits-property.md). Pivot прерывает отрисовку по достижении лимита. По умолчанию лимит составляет 10000 строк и 5000 столбцов. + +:::note +Лимиты применяются к большим наборам данных. Числа приблизительны — Pivot не гарантирует точного количества строк/столбцов. +::: + +Следующий фрагмент кода ограничивает набор данных 10 строками и 3 столбцами: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + limits: { rows: 10, columns: 3 } +}); +~~~ + +## Применение математических методов {#applying-maths-methods} + +### Методы по умолчанию {#default-methods} + +Pivot включает следующие встроенные методы агрегации: + +- `sum` (только числовые значения) — суммирует все выбранные значения; игнорирует пустые ячейки, логические значения вроде `TRUE` и текст +- `min` (числовые значения и даты) — возвращает минимальное значение; игнорирует пустые ячейки, логические значения и текст. Возвращает `0`, если во входных данных нет чисел +- `max` (числовые значения и даты) — возвращает максимальное значение; игнорирует пустые ячейки, логические значения и текст. Возвращает `0`, если во входных данных нет чисел +- `count` (числовые, текстовые значения и даты) — считает непустые ячейки; это метод по умолчанию, назначаемый каждому вновь добавленному полю +- `countunique` (числовые и текстовые значения) — считает количество уникальных значений во входных данных +- `average` (только числовые значения) — вычисляет среднее арифметическое; игнорирует пустые ячейки, логические значения и текст. Включает ячейки со значением ноль +- `counta` (числовые, текстовые значения и даты) — считает все непустые значения, включая числа, даты и текст +- `median` (только числовые значения) — возвращает медиану входных данных +- `product` (только числовые значения) — возвращает произведение всех чисел во входных данных +- `stdev` (только числовые значения) — стандартное отклонение, при котором входные данные рассматриваются как выборка из большей совокупности +- `stdevp` (только числовые значения) — стандартное отклонение, при котором входные данные рассматриваются как вся генеральная совокупность +- `var` (только числовые значения) — дисперсия, при которой входные данные рассматриваются как выборка из большей совокупности +- `varp` (только числовые значения) — дисперсия, при которой входные данные рассматриваются как вся генеральная совокупность + +Следующий фрагмент кода показывает определения встроенных методов: + +~~~jsx +const defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +Применяйте метод по умолчанию через параметр `values` свойства [`config`](api/config/config-property.md). См. раздел [Определение значений](#options-for-defining-values). + +Следующий фрагмент кода назначает `count` полю `title` и `max` полю `score`: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + // идентификатор поля + field: "title", + // метод + method: "count" + }, + { + id: "score", + method: "max" + } + ] + } +}); +~~~ + +### Определение значений {#options-for-defining-values} + +Каждую запись в `values` можно задать в одной из двух равнозначных форм: + +- строка вида `"operation(fieldID)"` +- объект `{ field: string, method: string }` (оба поля обязательны) + +Следующий фрагмент кода использует обе формы в одном массиве `values`: + +~~~jsx +values: [ + "sum(sales)", // первый вариант + { field: "sales", method: "sum" } // второй вариант +] +~~~ + +### Переопределение метода по умолчанию {#override-the-default-method} + +Для каждого вновь добавленного поля Pivot назначает первый доступный метод для данного типа данных. Чтобы изменить это поведение, перехватите событие `add-field` с помощью метода [`api.intercept`](api/internal/intercept-method.md). + +В примере ниже выполняется перехват `add-field` и принудительно устанавливается метод `max` при добавлении числового поля: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count", + }, + { + field: "score", + method: "max", + }, + ], + }, +}); +// переопределение метода по умолчанию для вновь добавляемых числовых полей +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "max"; + } +}); +~~~ + +### Добавление пользовательских математических методов {#add-custom-math-methods} + +Чтобы добавить пользовательский метод агрегации, используйте свойство [`methods`](api/config/methods-property.md). Каждая запись связывает имя метода (ключ) с объектом конфигурации, содержащим функцию `handler` и метаданные. Функция `handler` принимает массив значений и возвращает одно агрегированное значение. + +В примере ниже добавляются два метода, специфичных для дат. `countunique_date` считает уникальные даты по их числовым меткам времени. `average_date` возвращает среднюю дату путём усреднения меток времени: + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique", + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// показывать целые числа для результатов "count" и "unique count" +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// преобразование строковых дат в объекты Date +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +## Обработка данных с помощью предикатов {#processing-data-with-predicates} + +Предикаты — это функции предварительной обработки, которые преобразуют исходные данные полей до того, как Pivot использует их в строках или столбцах. Например, предикат может группировать даты по месяцам перед агрегацией. + +Следующий фрагмент кода показывает встроенные предикаты дат, применяемые Pivot по умолчанию: + +~~~jsx +const defaultPredicates = { + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +Чтобы добавить пользовательский предикат, настройте свойство [`predicates`](api/config/predicates-property.md). Каждая запись связывает идентификатор предиката (ключ) с объектом конфигурации: + +- `type` — типы полей, которые принимает предикат (`"number"`, `"date"`, `"text"` или массив) +- `label` — метка предиката, отображаемая в выпадающем списке GUI для строки/столбца +- `handler` — функция, преобразующая значение и возвращающая обработанное значение +- `template` — необязательная функция, управляющая отображением обработанного значения +- `field` — необязательная функция, ограничивающая предикат конкретными полями +- `filter` — необязательная конфигурация фильтра, если тип фильтра должен отличаться от `type` или формат данных должен отличаться от `template` + +Чтобы использовать пользовательский предикат, задайте его идентификатор как `method` строки или столбца, к которым предикат должен применяться. + +Следующий фрагмент кода регистрирует два пользовательских предиката (`monthYear` и `profitSign`) и применяет их в конфигурации `columns`: + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// преобразование строковых дат в объекты Date +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +## Добавление столбцов и строк с итоговыми значениями {#add-columns-and-rows-with-total-values} + +Используйте свойство [`tableShape`](api/config/tableshape-property.md), чтобы отрисовать итоговый столбец справа (`totalColumn: true`) или итоговую строку-футер (`totalRow: true`). + +Следующий фрагмент кода включает и итоговый столбец, и итоговую строку: + +~~~jsx {2-5} +const table = new pivot.Pivot("#root", { + tableShape: { + totalRow: true, + totalColumn: true + }, + fields, + data, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + } + ] + } +}); +~~~ + +## Пример {#example} + +Фрагмент ниже применяет пользовательские математические операции: + + + +**Связанные примеры**: + +- [Pivot 2. Набор данных с псевдонимами](https://snippet.dhtmlx.com/7vc68rqd) +- [Pivot 2. Определение форматов полей](https://snippet.dhtmlx.com/77nc4j8v) +- [Pivot 2. Внешний фильтр](https://snippet.dhtmlx.com/s7tc9g4z) +- [Pivot 2. Общий итог для столбцов и строк](https://snippet.dhtmlx.com/f0ag0t9t) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/working-with-server.md b/i18n/ru/docusaurus-plugin-content-docs/current/guides/working-with-server.md new file mode 100644 index 0000000..a02da6d --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/working-with-server.md @@ -0,0 +1,172 @@ +--- +sidebar_label: Работа с сервером +title: Работа с сервером +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать, как интегрировать Pivot с серверной частью. Изучайте руководства разработчика и справочник API, пробуйте примеры кода и живые демо, скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +Pivot работает полностью в браузере. Виджет принимает массив исходных строк и объект [`config`](/api/config/config-property) (строки / столбцы / значения) и агрегирует данные на стороне клиента. Встроенного транспортного слоя нет, однако публичное API предоставляет хуки для обмена данными с любым сервером. + +Типичная интеграция включает три части: + +1. **Загрузка** необработанных, неагрегированных данных с сервера при инициализации +2. **Сохранение конфига** при изменении макета пользователем, чтобы сессия восстанавливалась при следующем входе +3. **Сохранение агрегированной таблицы**, когда серверу нужен снимок свёрнутого результата + +## Загрузка необработанных данных с сервера {#load-raw-data-from-the-server} + +Свойство [`data`](/api/config/data-property) ожидает массив объектов-строк в исходном виде. Pivot самостоятельно агрегирует строки, поэтому сервер возвращает неразвёрнутые данные. + +Получите данные и поля с помощью `fetch` (или любого HTTP-клиента), а затем создайте виджет после получения ответа: + +~~~html +
+ + +~~~ + +Если сервер возвращает поля дат в виде строк ISO, преобразуйте их в экземпляры `Date` перед передачей массива в Pivot. Методы агрегации для полей типа дата требуют реальных значений `Date`: + +~~~jsx +data.forEach(row => { + if (typeof row.when === "string") row.when = new Date(row.when); +}); +~~~ + +:::info +**Смотрите также**: +- [Загрузка данных](/guides/loading-data) +- [Форматирование дат](/guides/localization#date-formatting) +::: + +## Сохранение макета пользователя для восстановления сессии {#save-the-users-layout-to-resume-the-session} + +Чтобы пользователи могли вернуться к оставленному макету, сохраняйте объект [`config`](/api/config/config-property) при каждом изменении. Событие [`update-config`](/api/events/update-config-event) срабатывает, когда пользователь редактирует макет через интерфейс. Полезная нагрузка — обработанный конфиг вида `{ rows, columns, values, filters }`. + +Используйте [`api.on()`](/api/internal/on-method) для наблюдения за событием без его изменения. Переключитесь на [`api.intercept()`](/api/internal/intercept-method), если обработчику необходимо изменить полезную нагрузку события. + +Пример ниже подписывается на событие `update-config` и отправляет новый макет на сервер: + +~~~html +
+ + +~~~ + +При следующем посещении верните сохранённый конфиг из `/config` и передайте его как свойство `config` при инициализации. Виджет запустится с предыдущим макетом. Если макет поступает уже после создания виджета, примените сохранённый конфиг с помощью метода [`setConfig()`](/api/methods/setconfig-method). + +Частые обновления могут перегружать сервер, когда пользователь перетаскивает поля в панели конфигурации. Оберните POST в таймер, чтобы дебаунсировать вызовы: + +~~~jsx +let saveTimer; +table.api.on("update-config", newConfig => { + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/config", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(newConfig), + }); + }, 300); +}); +~~~ + +:::note +Полезная нагрузка `update-config` — это *обработанный* конфиг: Pivot может нормализовать ссылки на поля до формы `{ field, method }`. Передавайте обработанную форму обратно как свойство `config` при инициализации. Дополнительное преобразование не требуется. +::: + +:::tip +Верните `false` из обработчика, чтобы заблокировать изменение макета. Используйте это для управления сохранением через серверную валидацию. +::: + +## Сохранение агрегированной таблицы {#save-the-aggregated-table} + +Иногда ценен сам *результат*: серверный кэш отображённой таблицы, периодический отчёт или экспортный конвейер. Событие [`render-table`](/api/events/render-table-event) срабатывает после завершения агрегации в Pivot и содержит полную свёрнутую таблицу: `columns`, строки `data`, `footer`, `split` и т.д. + +Пример ниже подписывается на `render-table` и отправляет снимок на сервер, пропуская начальный рендер: + +~~~jsx +const table = new pivot.Pivot("#root", { data, fields, config }); + +let firstRender = true; +let saveTimer; + +table.api.on("render-table", ({ config: tableConfig }) => { + // пропускаем начальный рендер, вызванный первой агрегацией + if (firstRender) { + firstRender = false; + return; + } + + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/snapshot", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + columns: tableConfig.columns, + data: tableConfig.data, + footer: tableConfig.footer, + split: tableConfig.split, + }), + }); + }, 300); +}); +~~~ + +:::note +Событие `render-table` срабатывает чаще, чем `update-config`. Оно запускается при каждом пересчёте, включая сортировку и раскрытие/сворачивание. Дебаунсируйте обработчик и пропускайте первый рендер, чтобы отправлять один POST на каждое реальное изменение. +::: + +:::tip +Верните `false` из обработчика, чтобы предотвратить рендеринг. Используйте это, когда сервер отклоняет снимок или для режимов только для чтения. +::: + +### Перезагрузка агрегированного снимка {#reload-an-aggregated-snapshot} + +Pivot создаёт агрегированные таблицы и не отображает предварительно агрегированные. Свойство [`data`](/api/config/data-property) всегда принимает исходные строки. Снимок, сохранённый из `render-table`, поэтому подходит для следующих случаев: + +- последующий экспортный конвейер (CSV, XLSX) на сервере +- представление только для чтения, отображаемое простой таблицей данных из сохранённых `columns` и `data` +- кэшированный отчёт, предоставляемый другим пользователям без повторного выполнения агрегации + +**Связанные статьи**: + +- [Загрузка данных](/guides/loading-data) +- [Экспорт данных](/guides/exporting-data) + +**Связанное API**: + +- [`api.on()`](/api/internal/on-method) +- [`update-config`](/api/events/update-config-event) +- [`render-table`](/api/events/render-table-event) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/how-to-start.md b/i18n/ru/docusaurus-plugin-content-docs/current/how-to-start.md new file mode 100644 index 0000000..b0130c3 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/how-to-start.md @@ -0,0 +1,122 @@ +--- +sidebar_label: Начало работы +title: Начало работы +description: Вы можете узнать, как начать работу с DHTMLX Pivot, в документации JavaScript-библиотеки DHTMLX Pivot. Изучайте руководства разработчика и справочник API, запускайте примеры кода и живые демо, а также скачайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Начало работы {#how-to-start} + +Это понятное и подробное руководство проведёт вас через все шаги, необходимые для размещения полнофункционального Pivot на странице. + +![pivot-main](/assets/pivot_main.png) + +## Шаг 1. Загрузка и установка пакетов {#step-1-downloading-and-installing-packages} + +[Загрузите пакет](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml) и распакуйте его в папку вашего проекта. + +Вы можете импортировать JavaScript Pivot в проект с помощью менеджера пакетов `yarn` или `npm`. + +:::info +Если вы хотите интегрировать Pivot в проекты React, Angular, Svelte или Vue, обратитесь к соответствующим [**руководствам по интеграции**](/category/integration-with-frameworks/) для получения дополнительной информации. +::: + +### Установка пробной версии Pivot через npm или yarn {#installing-trial-pivot-via-npm-or-yarn} + +:::info +Если вы хотите использовать пробную версию Pivot, загрузите [**пакет пробной версии Pivot**](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml) и следуйте инструкциям из файла *README*. Обратите внимание, что пробная версия Pivot доступна только в течение 30 дней. +::: + +### Установка PRO-версии Pivot через npm или yarn {#installing-pro-pivot-via-npm-or-yarn} + +:::info +Вы можете получить доступ к приватному **npm** DHTMLX напрямую в [Личном кабинете](https://dhtmlx.com/clients/), сгенерировав логин и пароль для **npm**. Там же доступно подробное руководство по установке. Обратите внимание, что доступ к приватному **npm** предоставляется только при наличии активной лицензии на Pivot. +::: + +## Шаг 2. Подключение исходных файлов {#step-2-including-source-files} + +Начните с создания HTML-файла и назовите его *index.html*. Затем подключите исходные файлы Pivot к созданному файлу. + +Необходимы два файла: + +- JS-файл Pivot +- CSS-файл Pivot + +~~~html {5-6} title="index.html" + + + + How to Start with Pivot + + + + + + + +~~~ + +## Шаг 3. Создание Pivot {#step-3-creating-pivot} + +Теперь вы готовы добавить Pivot на страницу. Сначала создадим DIV-контейнер для Pivot. + +~~~html {} title="index.html" + + + + How to Start with Pivot + + + + +
+ + + +~~~ + +## Шаг 4. Настройка Pivot {#step-4-configuring-pivot} + +Далее вы можете задать свойства конфигурации, которые должен иметь компонент Pivot при инициализации. + +Для начала работы с Pivot необходимо предоставить исходные данные. Пример ниже создаёт Pivot с: + +- строками для полей *studio* и *genre* +- столбцом *title* +- агрегацией значений для *score* с методом *max* + +Массив **fields** необходим для определения идентификаторов полей, подписей для отображения и типов данных. + +Массив **data** должен содержать фактические данные, отображаемые в виджете Pivot. Каждый объект массива представляет строку таблицы. + +Объект **config** определяет структуру таблицы Pivot: какие поля будут использоваться в качестве строк и столбцов таблицы, а также какие методы агрегации данных применяются к полям. + +~~~jsx +const table = new pivot.Pivot("#root", { + //свойства конфигурации + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## Что дальше {#whats-next} + +Вот и всё. Всего несколько простых шагов — и у вас есть удобный инструмент для анализа данных. Теперь вы можете приступить к решению своих задач или продолжить изучение возможностей JavaScript Pivot: + +- Страницы раздела [Руководства](/category/guides) содержат инструкции по установке, загрузке данных, стилизации и другие полезные советы для работы с конфигурацией Pivot +- [Справочник API](api/overview/main-overview.md) содержит описание функциональности Pivot diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/index.md b/i18n/ru/docusaurus-plugin-content-docs/current/index.md new file mode 100644 index 0000000..9477c06 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/index.md @@ -0,0 +1,103 @@ +--- +sidebar_label: Обзор Pivot +title: Обзор JavaScript Pivot +slug: / +description: Ознакомьтесь с обзором библиотеки DHTMLX JavaScript Pivot в документации. Изучите руководства разработчика и справочник API, опробуйте примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Обзор DHTMLX Pivot + +JavaScript Pivot — готовый компонент для создания сводных таблиц из больших наборов данных. API виджета легко адаптируется под нужды вашего веб-приложения. Компонент предоставляет конечному пользователю инструменты для сравнения и анализа сложных данных в рамках одной таблицы. + +## Структура Pivot {#pivot-structure} + +Интерфейс Pivot состоит из двух основных компонентов: панели настройки и таблицы с данными. + +![Main](assets/pivot-main.png) + +## Панель настройки {#configuration-panel} + +Панель настройки позволяет добавлять столбцы и строки в таблицу, а также поля значений, определяющих методы агрегации данных. Каждый элемент можно добавить через соответствующие области панели: + +- Значения: можно добавить значения, определяющие способ агрегации данных (например, сумма, минимум, максимум) +- Столбцы: можно настроить столбцы таблицы (указать, какие поля будут применяться в качестве столбцов) +- Строки: можно настроить, какие поля будут применяться в качестве строк таблицы + +Чтобы скрыть панель настройки, нажмите кнопку **Hide Settings**: + +![config_panel](assets/config_panel.png) + +### Область значений {#values-area} + +В области **Values** можно определить, какие методы агрегации (например, min, max, count) будут применяться к ячейкам сводной таблицы. Доступны следующие операции: + +- добавление и удаление полей из области значений +- изменение порядка и приоритета значений в таблице +- фильтрация данных +- настройка операций, применяемых к полям таблицы + +Подробнее см. в разделах [Операции в областях](#operations-in-areas) и [Фильтры](#filters). + +### Область столбцов {#columns-area} + +В области **Columns** доступны следующие операции: + +- добавление и удаление столбцов (то есть полей, применяемых в качестве столбцов) +- изменение порядка и приоритета столбцов в таблице +- фильтрация данных + +Подробнее см. в разделах [Операции в областях](#operations-in-areas) и [Фильтры](#filters). + +### Область строк {#rows-area} + +В панели настройки для области **Rows** доступны следующие операции: + +- добавление и удаление строк (то есть полей, применяемых в качестве строк) +- изменение порядка и приоритета строк в таблице +- фильтрация данных + +Подробнее см. в разделах [Операции в областях](#operations-in-areas) и [Фильтры](#filters). + +### Операции в областях {#operations-in-areas} + +Во всех трёх областях панели настройки можно добавлять и удалять поля из таблицы. Если нужно, чтобы поле применялось в качестве строки или столбца, выберите его в соответствующей области (столбцы или строки). + +Чтобы добавить новое поле, нажмите кнопку «+» в нужной области и выберите название из выпадающего списка. + +Чтобы удалить элемент, нажмите кнопку удаления («x»). + +![add_remove](assets/add_remove.png) + +Чтобы изменить порядок значений/строк/столбцов в таблице, перетащите элемент на нужную позицию. Чем левее элемент расположен в панели инструментов области, тем выше его приоритет и позиция в таблице. + +![priority](assets/priority.png) + +Чтобы задать операции, применяемые ко всем данным столбца таблицы, в области **Values** нажмите на операцию для нужного поля в выпадающем списке и выберите требуемый вариант. + +![operations](assets/operations.png) + +### Фильтры {#filters} + +Фильтры отображаются в виде выпадающих списков для каждого поля во всех областях. Pivot поддерживает следующие типы условий фильтрации: + +- для текстовых значений: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith +- для числовых значений: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains, begins with, not begins with, ends with, not ends with +- для дат: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween + +Чтобы отфильтровать данные в таблице, нажмите на значок фильтра нужного элемента в требуемой области, затем выберите оператор, задайте значение для фильтрации и нажмите **Apply**. Поля, к которым применена фильтрация, будут отмечены специальным значком фильтра. + +![filters](assets/filter.png) + +## Таблица {#table} + +Данные в таблице отображаются в соответствии с настройками, заданными в панели настройки. **Сортировка** по столбцам включается нажатием на заголовок столбца: + +![table](assets/table.png) + +## Что дальше {#whats-next} + +Теперь можно приступить к интеграции Pivot в ваше приложение. Следуйте инструкциям руководства [Как начать работу](how-to-start.md). + +Используя функциональность, предоставляемую API виджета, вы можете создать привлекательную сводную таблицу с расширенными возможностями, как в примере ниже: + + diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/news/migration.md b/i18n/ru/docusaurus-plugin-content-docs/current/news/migration.md new file mode 100644 index 0000000..6b225cb --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/news/migration.md @@ -0,0 +1,57 @@ +--- +sidebar_label: Миграция на новые версии +title: Миграция на новые версии +description: В документации библиотеки DHTMLX JavaScript Pivot вы можете узнать о миграции на новые версии. Ознакомьтесь с руководствами разработчика и справочником по API, изучите примеры кода и живые демо, а также загрузите бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Миграция на новые версии {#migration-to-newer-versions} + +## 2.0 -> 2.1 {#20---21} + +- Параметр `colWidth` объекта `sizes` в свойстве `tableShape` переименован в `columnWidth` + +## 1.5 -> 2.0 {#15---20} + +Этот список изменений поможет вам выполнить миграцию с предыдущей версии Pivot 1.5 на полностью обновлённую версию Pivot 2.0 + +:::note +Воспользуйтесь нашим [конвертером для миграции данных из версии 1.5](https://snippet.dhtmlx.com/s4sfdhq4) +::: + +### Изменённое API {#changed-api} + +#### Свойства {#properties} + +Новые свойства не являются полными аналогами предыдущих, но предоставляют расширенную функциональность. + +- [fieldList](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldlist_config.html) -> [fields](api/config/fields-property.md) +- [fields](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fields_config.html) -> [config](api/config/config-property.md) +- [mark](https://docs.dhtmlx.com/pivot/1-5/api__pivot_mark_config.html) -> параметр `marks` свойства [tableShape](api/config/tableshape-property.md) +- [types](https://docs.dhtmlx.com/pivot/1-5/api__pivot_types_config.html) -> [methods](api/config/methods-property.md) +- [layout](https://docs.dhtmlx.com/pivot/1-5/api__pivot_layout_config.html) -> [columnShape](api/config/columnshape-property.md), [headerShape](api/config/headershape-property.md), [readonly](api/config/readonly-property.md) +- [customFormat](https://docs.dhtmlx.com/pivot/1-5/api__pivot_customformat_config.html) -> [predicates](api/config/predicates-property.md) - пользовательские функции предварительной обработки данных + +#### События {#events} + +- [filterApply](https://docs.dhtmlx.com/pivot/1-5/api__pivot_filterapply_event.html) -> [apply-filter](api/events/apply-filter-event.md) +- [fieldClick](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldclick_event.html) -> идентичного события нет, но вы можете обратиться к [update-field](api/events/update-field-event.md) + +### Удалённое API {#removed-api} + +- [Методы версии 1.5](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_methods.html) являются устаревшими, все новые методы доступны здесь: [Методы](api/overview/main-overview.md#pivot-methods) +- [События Pivot 1.5](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_events.html) (`change`, `fieldClick`, `applyButtonClick`) более не доступны в Pivot 2.0, однако в новой версии вы найдёте расширенную функциональность (см. [события Pivot](api/overview/events-overview.md)) + +### Важные возможности {#important-features} + +- Экспорт данных: [предыдущий вариант экспорта](https://docs.dhtmlx.com/pivot/1-5/guides__export.html) -> [новый вариант экспорта](guides/exporting-data.md) +- Сортировка: [сортировка полей](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringfields) -> [сортировка данных](guides/working-with-data.md#sorting-data) +- Режим дерева: [gridMode](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#gridmode) -> [включение режима дерева](guides/configuration.md#enabling-the-tree-mode) +- Формат даты: [настройка полей с датами](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringdatefields) -> +[настройка формата даты](guides/localization.md#date-formatting) +- Кастомизация: + - [форматирование ячеек](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#conditionalformattingofcells) -> [стиль ячеек](guides/stylization.md#cell-style) + - [шаблоны для заголовков](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforheaders) -> + [применение шаблонов к заголовкам](guides/configuration.md#applying-templates-to-headers) + - [шаблоны для ячеек](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforcells) -> + [применение шаблонов к ячейкам](guides/configuration.md#applying-templates-to-cells) +- Фильтрация: [работа с фильтрами](https://docs.dhtmlx.com/pivot/1-5/guides__using_filters.html) -> [фильтрация данных](guides/working-with-data.md#filtering-data) diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/news/whats-new.md b/i18n/ru/docusaurus-plugin-content-docs/current/news/whats-new.md new file mode 100644 index 0000000..ee9c1e5 --- /dev/null +++ b/i18n/ru/docusaurus-plugin-content-docs/current/news/whats-new.md @@ -0,0 +1,114 @@ +--- +sidebar_label: Что нового +title: Что нового +description: Вы можете ознакомиться с новыми возможностями DHTMLX Pivot и историей его выпусков в документации библиотеки DHTMLX JavaScript UI. Изучайте руководства для разработчиков и справочник по API, пробуйте примеры кода и живые демо, а также загружайте бесплатную 30-дневную ознакомительную версию DHTMLX Pivot. +--- + +# Что нового {#whats-new} + +Если вы обновляете Pivot с более старой версии, ознакомьтесь со страницей [Миграция на новые версии](news/migration.md) для получения подробной информации. + +## Версия 2.1.1 {#version-211} + +Выпущена 10 июня 2026 г. + +### Исправления {#fixes} + +- Возникает ошибка "getMonth" при применении фильтров строк к наборам данных с отсутствующими или пустыми значениями + +## Версия 2.1 {#version-21} + +Выпущена 6 мая 2025 г. + +### Новая функциональность {#new-functionality} + +- [Возможность фиксировать столбцы справа](guides/configuration.md#freezing-columns-on-the-right) +- [Выравнивание по умолчанию](guides/stylization.md#specific-css-classes) и [форматирование на основе локали](guides/localization.md#number-formatting) для числовых значений +- [Возможность задавать пользовательские числовые форматы](guides/working-with-data.md#applying-formats-to-fields) (для полей дат и числовых полей) через параметр `format`, добавленный в свойство [`fields`](api/config/fields-property.md) +- [Возможность стилизовать ячейки заголовка и таблицы](guides/stylization.md#cell-style) с помощью параметра `cellStyle` свойств [`tableShape`](api/config/tableshape-property.md) и [`headerShape`](api/config/headershape-property.md) +- Возможность вставлять HTML-содержимое в ячейки заголовка и таблицы с помощью вспомогательного метода [`pivot.template`](api/helpers/template.md), определяя шаблон в свойстве `cell` объектов заголовка и столбца (настройка таблицы путём перехвата события [render-table](api/events/render-table-event.md)) +- [Расширены настройки экспорта в Excel и CSV](guides/exporting-data.md): + - для формата "xlsx" поля дат и числовые поля экспортируются как необработанные значения с форматом по умолчанию или форматом, заданным через свойство [`fields`](api/config/fields-property.md) + - возможность задавать имена файла и листа, а также исключать верхний/нижний колонтитул из экспортируемого файла + - возможность добавлять стили и шаблоны для экспортируемых ячеек +- [Возможность фильтровать данные через внешний элемент ввода](api/table/filter-rows.md) +- Визуальная рамка при навигации по ячейкам +- [Интеграция с фреймворками](/category/integration-with-frameworks) + +### Новый API {#new-api} + +- Параметр `right` внутри объекта `split` свойства [`tableShape`](api/config/tableshape-property.md) +- Параметр `cellStyle` внутри свойств [`tableShape`](api/config/tableshape-property.md) и [`headerShape`](api/config/headershape-property.md) +- Параметр `format` внутри массива [`fields`](api/config/fields-property.md) +- Событие [`filter-rows`](api/table/filter-rows.md) внутреннего компонента Table +- [`pivot.template`](api/helpers/template.md) для определения HTML-содержимого ячеек таблицы + +### Исправления {#fixes-21} + +- Итоговые столбцы не сортируются +- Строковые значения с ведущим нулём преобразуются в числа при экспорте +- Шаблон предиката не применяется к строкам/столбцам +- Ошибка наблюдателя изменения размеров в граничных случаях + +### Критические изменения {#breaking-changes} + +- Параметр `colWidth` объекта `sizes` в свойстве `tableShape` переименован в `columnWidth` + +## Версия 2.0.3 {#version-203} + +Выпущена 29 ноября 2024 г. + +### Исправления {#fixes-203} + +- При экспорте в Excel/CSV древовидной структуры экспортируются только верхние ветви +- Экспортируемые столбцы с автоматической шириной оказываются слишком узкими в итоговом файле Excel +- Неверное положение всплывающего окна с фильтрами +- Некорректное поведение после изменения конфигурации с помощью метода setConfig +- Более точные определения типов + +## Версия 2.0.2 {#version-202} + +Выпущена 22 октября 2024 г. + +### Исправления {#fixes-202} + +- Определение типа `columnShape` +- Корректное содержимое пакета + +## Версия 2.0 {#version-20} + +Выпущена 26 августа 2024 г. + +Пожалуйста, ознакомьтесь с обзором выпуска на [странице блога](https://dhtmlx.com/blog/) + +### Критическое изменение {#breaking-change} + +:::note +API версии 1.5 несовместим с API версии 2.0. +::: + +Советы по миграции на новую версию смотрите на странице [Миграция](news/migration.md). + +### Новая функциональность {#new-functionality-20} + +- Pivot 2.0 быстро выполняет рендеринг и генерацию больших наборов данных ([пример](https://snippet.dhtmlx.com/e6qwqrys)) +- Новые возможности настройки внешнего вида и поведения столбцов доступны через свойство [`columnShape`](api/config/columnshape-property.md): + - настройка **autowidth** с возможностью задать maxRows для обработки при расчёте **autoWidth** ([пример](https://snippet.dhtmlx.com/tn1yw14m)) + - функция **firstOnly**, при которой каждое поле с одинаковыми данными анализируется только один раз для расчёта ширины столбца (по умолчанию) +- Теперь можно настраивать внешний вид и поведение заголовков с помощью свойства [`headerShape`](api/config/headershape-property.md), которое позволяет: + - применять шаблон к тексту в заголовках ([пример](https://snippet.dhtmlx.com/g89r9ryw)) + - изменять ориентацию текста ([пример](https://snippet.dhtmlx.com/4qroi8ka)) + - делать столбцы сворачиваемыми ([пример](https://snippet.dhtmlx.com/pt2ljmcm)) +- Форма и размеры таблицы настраиваются через свойство [`tableShape`](api/config/tableshape-property.md), которое позволяет: + - настраивать высоту строк, заголовков, нижнего колонтитула: rowHeight, headerHeight, footerHeight ([Изменение размеров таблицы](guides/configuration.md#resizing-the-table)) + - генерировать итоговые значения не только для столбцов, но и для строк — с помощью параметра **totalColumn** свойства `tableShape` ([пример](https://snippet.dhtmlx.com/f0ag0t9t)) + - скрывать дублирующиеся значения в представлении таблицы (параметр **cleanRows** свойства [`tableShape`](api/config/tableshape-property.md)) + - фиксировать столбцы слева, делая их статичными при прокрутке ([пример](https://snippet.dhtmlx.com/lahf729o)) + - разворачивать или сворачивать все строки ([пример](https://snippet.dhtmlx.com/i4mi6ejn)) +- Добавлены дополнительные возможности для агрегирования данных: + - [ограничение загружаемых данных](guides/working-with-data.md#limiting-loaded-data) + - доступно больше [операций с данными](guides/working-with-data.md#applying-maths-methods) + - [обработка данных с помощью предикатов](guides/working-with-data.md#processing-data-with-predicates) — применение пользовательских функций предварительной обработки данных + - [задание формата даты через локаль](guides/localization.md#date-formatting) +- Добавлены новые методы: [`getTable()`](api/methods/gettable-method.md), [`setConfig()`](api/methods/setconfig-method.md), [`setLocale()`](api/methods/setlocale-method.md), [`showConfigPanel()`](api/methods/showconfigpanel-method.md) +- Добавлены новые события: [`add-field`](api/events/add-field-event.md), [`delete-field`](api/events/delete-field-event.md), [`open-filter`](api/events/open-filter-event.md), [`render-table`](api/events/render-table-event.md), [`move-field`](api/events/move-field-event.md), [`show-config-panel`](api/events/show-config-panel-event.md), [`show-config-panel`](api/events/show-config-panel-event.md), [`update-config`](api/events/update-config-event.md), [`update-field`](api/events/update-field-event.md). diff --git a/i18n/ru/docusaurus-theme-classic/footer.json b/i18n/ru/docusaurus-theme-classic/footer.json new file mode 100644 index 0000000..839baf2 --- /dev/null +++ b/i18n/ru/docusaurus-theme-classic/footer.json @@ -0,0 +1,62 @@ +{ + "link.title.Development center": { + "message": "Центр разработки", + "description": "The title of the footer links column with title=Development center in the footer" + }, + "link.title.Community": { + "message": "Сообщество", + "description": "The title of the footer links column with title=Community in the footer" + }, + "link.title.Company": { + "message": "Компания", + "description": "The title of the footer links column with title=Company in the footer" + }, + "link.item.label.Download JS Pivot": { + "message": "Скачать JS Pivot", + "description": "The label of footer link with label=Download JS Pivot linking to https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml" + }, + "link.item.label.Examples": { + "message": "Примеры", + "description": "The label of footer link with label=Examples linking to https://snippet.dhtmlx.com/mhymus00?tag=pivot" + }, + "link.item.label.Blog": { + "message": "Блог", + "description": "The label of footer link with label=Blog linking to https://dhtmlx.com/blog/tag/pivot/" + }, + "link.item.label.Forum": { + "message": "Форум", + "description": "The label of footer link with label=Forum linking to https://forum.dhtmlx.com/c/pivot/16" + }, + "link.item.label.GitHub": { + "message": "GitHub", + "description": "The label of footer link with label=GitHub linking to https://github.com/DHTMLX" + }, + "link.item.label.Youtube": { + "message": "Youtube", + "description": "The label of footer link with label=Youtube linking to https://www.youtube.com/user/dhtmlx" + }, + "link.item.label.Facebook": { + "message": "Facebook", + "description": "The label of footer link with label=Facebook linking to https://www.facebook.com/dhtmlx" + }, + "link.item.label.Twitter": { + "message": "Twitter", + "description": "The label of footer link with label=Twitter linking to https://twitter.com/dhtmlx" + }, + "link.item.label.Linkedin": { + "message": "Linkedin", + "description": "The label of footer link with label=Linkedin linking to https://www.linkedin.com/groups/3345009/" + }, + "link.item.label.About us": { + "message": "О нас", + "description": "The label of footer link with label=About us linking to https://dhtmlx.com/docs/company.shtml" + }, + "link.item.label.Contact us": { + "message": "Связаться с нами", + "description": "The label of footer link with label=Contact us linking to https://dhtmlx.com/docs/contact.shtml" + }, + "link.item.label.Licensing": { + "message": "Лицензирование", + "description": "The label of footer link with label=Licensing linking to https://dhtmlx.com/docs/products/dhtmlxPivot/#licensing" + } +} diff --git a/i18n/ru/docusaurus-theme-classic/navbar.json b/i18n/ru/docusaurus-theme-classic/navbar.json new file mode 100644 index 0000000..eacaa53 --- /dev/null +++ b/i18n/ru/docusaurus-theme-classic/navbar.json @@ -0,0 +1,26 @@ +{ + "title": { + "message": "Документация JavaScript Pivot", + "description": "The title in the navbar" + }, + "logo.alt": { + "message": "Логотип DHTMLX JavaScript Pivot", + "description": "The alt text of navbar logo" + }, + "item.label.Examples": { + "message": "Примеры", + "description": "Navbar item with label Examples" + }, + "item.label.Forum": { + "message": "Форум", + "description": "Navbar item with label Forum" + }, + "item.label.Support": { + "message": "Поддержка", + "description": "Navbar item with label Support" + }, + "item.label.Download": { + "message": "Скачать", + "description": "Navbar item with label Download" + } +} diff --git a/i18n/zh/code.json b/i18n/zh/code.json new file mode 100644 index 0000000..9a9dd4d --- /dev/null +++ b/i18n/zh/code.json @@ -0,0 +1,364 @@ +{ + "theme.ErrorPageContent.title": { + "message": "此页面崩溃了。", + "description": "The title of the fallback page when the page crashed" + }, + "theme.BackToTopButton.buttonAriaLabel": { + "message": "滚动回顶部", + "description": "The ARIA label for the back to top button" + }, + "theme.blog.archive.title": { + "message": "存档", + "description": "The page & hero title of the blog archive page" + }, + "theme.blog.archive.description": { + "message": "存档", + "description": "The page & hero description of the blog archive page" + }, + "theme.blog.paginator.navAriaLabel": { + "message": "博客列表页面导航", + "description": "The ARIA label for the blog pagination" + }, + "theme.blog.paginator.newerEntries": { + "message": "更新的文章", + "description": "The label used to navigate to the newer blog posts page (previous page)" + }, + "theme.blog.paginator.olderEntries": { + "message": "更早的文章", + "description": "The label used to navigate to the older blog posts page (next page)" + }, + "theme.blog.post.paginator.navAriaLabel": { + "message": "博客文章页面导航", + "description": "The ARIA label for the blog posts pagination" + }, + "theme.blog.post.paginator.newerPost": { + "message": "更新的文章", + "description": "The blog post button label to navigate to the newer/previous post" + }, + "theme.blog.post.paginator.olderPost": { + "message": "更早的文章", + "description": "The blog post button label to navigate to the older/next post" + }, + "theme.tags.tagsPageLink": { + "message": "查看所有标签", + "description": "The label of the link targeting the tag list page" + }, + "theme.colorToggle.ariaLabel.mode.system": { + "message": "系统模式", + "description": "The name for the system color mode" + }, + "theme.colorToggle.ariaLabel.mode.light": { + "message": "浅色模式", + "description": "The name for the light color mode" + }, + "theme.colorToggle.ariaLabel.mode.dark": { + "message": "深色模式", + "description": "The name for the dark color mode" + }, + "theme.colorToggle.ariaLabel": { + "message": "切换深色和浅色模式(当前为 {mode})", + "description": "The ARIA label for the color mode toggle" + }, + "theme.docs.breadcrumbs.navAriaLabel": { + "message": "面包屑导航", + "description": "The ARIA label for the breadcrumbs" + }, + "theme.docs.DocCard.categoryDescription.plurals": { + "message": "个项目", + "description": "The default description for a category card in the generated index about how many items this category includes" + }, + "theme.docs.paginator.navAriaLabel": { + "message": "文档页面", + "description": "The ARIA label for the docs pagination" + }, + "theme.docs.paginator.previous": { + "message": "上一页", + "description": "The label used to navigate to the previous doc" + }, + "theme.docs.paginator.next": { + "message": "下一页", + "description": "The label used to navigate to the next doc" + }, + "theme.docs.tagDocListPageTitle.nDocsTagged": { + "message": "一个文档被标记|{count} 个文档被标记", + "description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.docs.tagDocListPageTitle": { + "message": "带有“{tagName}”的 {nDocsTagged}", + "description": "The title of the page for a docs tag" + }, + "theme.docs.versionBadge.label": { + "message": "版本: {versionLabel}" + }, + "theme.docs.versions.unreleasedVersionLabel": { + "message": "这是 {siteTitle} {versionLabel} 版本的未发布文档。", + "description": "The label used to tell the user that he's browsing an unreleased doc version" + }, + "theme.docs.versions.unmaintainedVersionLabel": { + "message": "这是 {siteTitle} {versionLabel} 的文档,该版本已不再维护。", + "description": "The label used to tell the user that he's browsing an unmaintained doc version" + }, + "theme.docs.versions.latestVersionSuggestionLabel": { + "message": "有关最新文档,请参见 {latestVersionLink}({versionLabel})。", + "description": "The label used to tell the user to check the latest version" + }, + "theme.docs.versions.latestVersionLinkLabel": { + "message": "最新版本", + "description": "The label used for the latest version suggestion link label" + }, + "theme.common.editThisPage": { + "message": "编辑此页面", + "description": "The link label to edit the current page" + }, + "theme.common.headingLinkTitle": { + "message": "直达链接至 {heading}", + "description": "Title for link to heading" + }, + "theme.lastUpdated.atDate": { + "message": " 于 {date}", + "description": "The words used to describe on which date a page has been last updated" + }, + "theme.lastUpdated.byUser": { + "message": " 由 {user}", + "description": "The words used to describe by who the page has been last updated" + }, + "theme.lastUpdated.lastUpdatedAtBy": { + "message": "最后更新于{atDate}{byUser}", + "description": "The sentence used to display when a page has been last updated, and by who" + }, + "theme.navbar.mobileVersionsDropdown.label": { + "message": "版本", + "description": "The label for the navbar versions dropdown on mobile view" + }, + "theme.NotFound.title": { + "message": "页面未找到", + "description": "The title of the 404 page" + }, + "theme.tags.tagsListLabel": { + "message": "标签:", + "description": "The label alongside a tag list" + }, + "theme.admonition.caution": { + "message": "注意", + "description": "The default label used for the Caution admonition (:::caution)" + }, + "theme.admonition.danger": { + "message": "危险", + "description": "The default label used for the Danger admonition (:::danger)" + }, + "theme.admonition.info": { + "message": "信息", + "description": "The default label used for the Info admonition (:::info)" + }, + "theme.admonition.note": { + "message": "注释", + "description": "The default label used for the Note admonition (:::note)" + }, + "theme.admonition.tip": { + "message": "提示", + "description": "The default label used for the Tip admonition (:::tip)" + }, + "theme.admonition.warning": { + "message": "警告", + "description": "The default label used for the Warning admonition (:::warning)" + }, + "theme.AnnouncementBar.closeButtonAriaLabel": { + "message": "关闭", + "description": "The ARIA label for close button of announcement bar" + }, + "theme.blog.sidebar.navAriaLabel": { + "message": "博客最新文章导航", + "description": "The ARIA label for recent posts in the blog sidebar" + }, + "theme.DocSidebarItem.expandCategoryAriaLabel": { + "message": "展开侧边栏类别 '{label}'", + "description": "The ARIA label to expand the sidebar category" + }, + "theme.DocSidebarItem.collapseCategoryAriaLabel": { + "message": "折叠侧边栏类别 '{label}'", + "description": "The ARIA label to collapse the sidebar category" + }, + "theme.IconExternalLink.ariaLabel": { + "message": "(在新标签页中打开)", + "description": "The ARIA label for the external link icon" + }, + "theme.NavBar.navAriaLabel": { + "message": "主导航", + "description": "The ARIA label for the main navigation" + }, + "theme.navbar.mobileLanguageDropdown.label": { + "message": "语言", + "description": "The label for the mobile language switcher dropdown" + }, + "theme.NotFound.p1": { + "message": "我们无法找到您要查找的内容。", + "description": "The first paragraph of the 404 page" + }, + "theme.NotFound.p2": { + "message": "请联系将您链接到原始URL的网站所有者,告知他们的链接已失效。", + "description": "The 2nd paragraph of the 404 page" + }, + "theme.TOCCollapsible.toggleButtonLabel": { + "message": "本页内容", + "description": "The label used by the button on the collapsible TOC component" + }, + "theme.blog.post.readingTime.plurals": { + "message": "阅读时间1分钟|阅读时间 {readingTime} 分钟", + "description": "Pluralized label for \"{readingTime} min read\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.blog.post.readMore": { + "message": "阅读更多", + "description": "The label used in blog post item excerpts to link to full blog posts" + }, + "theme.blog.post.readMoreLabel": { + "message": "阅读关于 {title} 的更多内容", + "description": "The ARIA label for the link to full blog posts from excerpts" + }, + "theme.CodeBlock.copy": { + "message": "复制", + "description": "The copy button label on code blocks" + }, + "theme.CodeBlock.copied": { + "message": "已复制", + "description": "The copied button label on code blocks" + }, + "theme.CodeBlock.copyButtonAriaLabel": { + "message": "复制代码到剪贴板", + "description": "The ARIA label for copy code blocks button" + }, + "theme.CodeBlock.wordWrapToggle": { + "message": "切换自动换行", + "description": "The title attribute for toggle word wrapping button of code block lines" + }, + "theme.docs.breadcrumbs.home": { + "message": "首页", + "description": "The ARIA label for the home page in the breadcrumbs" + }, + "theme.docs.sidebar.collapseButtonTitle": { + "message": "折叠侧边栏", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.collapseButtonAriaLabel": { + "message": "折叠侧边栏", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.navAriaLabel": { + "message": "文档侧边栏", + "description": "The ARIA label for the sidebar navigation" + }, + "theme.docs.sidebar.closeSidebarButtonAriaLabel": { + "message": "关闭导航栏", + "description": "The ARIA label for close button of mobile sidebar" + }, + "theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": { + "message": "← 返回主菜单", + "description": "The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)" + }, + "theme.docs.sidebar.toggleSidebarButtonAriaLabel": { + "message": "切换导航栏", + "description": "The ARIA label for hamburger menu button of mobile navigation" + }, + "theme.navbar.mobileDropdown.collapseButton.expandAriaLabel": { + "message": "展开下拉菜单", + "description": "The ARIA label of the button to expand the mobile dropdown navbar item" + }, + "theme.navbar.mobileDropdown.collapseButton.collapseAriaLabel": { + "message": "折叠下拉菜单", + "description": "The ARIA label of the button to collapse the mobile dropdown navbar item" + }, + "theme.docs.sidebar.expandButtonTitle": { + "message": "展开侧边栏", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.docs.sidebar.expandButtonAriaLabel": { + "message": "展开侧边栏", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.SearchBar.noResultsText": { + "message": "没有找到任何文档" + }, + "theme.SearchBar.seeAllOutsideContext": { + "message": "查看“{context}”以外的全部结果" + }, + "theme.SearchBar.searchInContext": { + "message": "查看“{context}”以内的全部结果" + }, + "theme.SearchBar.seeAll": { + "message": "查看全部 {count} 个结果" + }, + "theme.SearchBar.label": { + "message": "搜索", + "description": "The ARIA label and placeholder for search button" + }, + "theme.SearchPage.existingResultsTitle": { + "message": "\"{query}\" 的搜索结果", + "description": "The search page title for non-empty query" + }, + "theme.SearchPage.emptyResultsTitle": { + "message": "搜索文档", + "description": "The search page title for empty query" + }, + "theme.SearchPage.searchContext.everywhere": { + "message": "所有" + }, + "theme.SearchPage.documentsFound.plurals": { + "message": "找到一篇文档|找到 {count} 篇文档", + "description": "Pluralized label for \"{count} documents found\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.SearchPage.noResultsText": { + "message": "未找到结果", + "description": "The paragraph for empty search result" + }, + "theme.blog.post.plurals": { + "message": "一篇文章|{count} 篇文章", + "description": "Pluralized label for \"{count} posts\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)" + }, + "theme.blog.tagTitle": { + "message": "带有“{tagName}”标签的 {nPosts} 篇文章", + "description": "The title of the page for a blog tag" + }, + "theme.blog.author.pageTitle": { + "message": "{authorName} - {nPosts}", + "description": "The title of the page for a blog author" + }, + "theme.blog.authorsList.pageTitle": { + "message": "作者", + "description": "The title of the authors page" + }, + "theme.blog.authorsList.viewAll": { + "message": "查看所有作者", + "description": "The label of the link targeting the blog authors page" + }, + "theme.blog.author.noPosts": { + "message": "该作者尚未撰写任何文章。", + "description": "The text for authors with 0 blog post" + }, + "theme.contentVisibility.unlistedBanner.title": { + "message": "非公开页面", + "description": "The unlisted content banner title" + }, + "theme.contentVisibility.unlistedBanner.message": { + "message": "此页面为非公开。搜索引擎不会索引它,只有拥有直接链接的用户可以访问。", + "description": "The unlisted content banner message" + }, + "theme.contentVisibility.draftBanner.title": { + "message": "草稿页面", + "description": "The draft content banner title" + }, + "theme.contentVisibility.draftBanner.message": { + "message": "此页面为草稿,仅在开发环境可见,并且不会包含在生产构建中。", + "description": "The draft content banner message" + }, + "theme.ErrorPageContent.tryAgain": { + "message": "再试一次", + "description": "The label of the button to try again rendering when the React error boundary captures an error" + }, + "theme.common.skipToMainContent": { + "message": "跳至主要内容", + "description": "The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation" + }, + "theme.tags.tagsPageTitle": { + "message": "标签", + "description": "The title of the tag list page" + } +} diff --git a/i18n/zh/docusaurus-plugin-content-blog/options.json b/i18n/zh/docusaurus-plugin-content-blog/options.json new file mode 100644 index 0000000..d7d0a51 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-blog/options.json @@ -0,0 +1,14 @@ +{ + "title": { + "message": "博客", + "description": "The title for the blog used in SEO" + }, + "description": { + "message": "博客", + "description": "The description for the blog used in SEO" + }, + "sidebar.title": { + "message": "最近的文章", + "description": "The label for the left sidebar" + } +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/current.json b/i18n/zh/docusaurus-plugin-content-docs/current.json new file mode 100644 index 0000000..dbfdcb5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current.json @@ -0,0 +1,70 @@ +{ + "version.label": { + "message": "下一个", + "description": "The label for version current" + }, + "sidebar.docs.category.What's new and migration": { + "message": "新功能和迁移", + "description": "The label for category 'What's new and migration' in sidebar 'docs'" + }, + "sidebar.docs.category.What's new and migration.link.generated-index.title": { + "message": "新功能和迁移", + "description": "The generated-index page title for category 'What's new and migration' in sidebar 'docs'" + }, + "sidebar.docs.category.API": { + "message": "API", + "description": "The label for category 'API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot methods": { + "message": "Pivot 方法", + "description": "The label for category 'Pivot methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API": { + "message": "Pivot 内部 API", + "description": "The label for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API.link.generated-index.title": { + "message": "内部 API 概述", + "description": "The generated-index page title for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Event Bus methods": { + "message": "事件总线方法", + "description": "The label for category 'Event Bus methods' in sidebar 'docs'" + }, + "sidebar.docs.category.State methods": { + "message": "状态方法", + "description": "The label for category 'State methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot events": { + "message": "Pivot 事件", + "description": "The label for category 'Pivot events' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot properties": { + "message": "Pivot 属性", + "description": "The label for category 'Pivot properties' in sidebar 'docs'" + }, + "sidebar.docs.category.Table events": { + "message": "Table 事件", + "description": "The label for category 'Table events' in sidebar 'docs'" + }, + "sidebar.docs.category.Helpers": { + "message": "辅助函数", + "description": "The label for category 'Helpers' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks": { + "message": "与框架集成", + "description": "The label for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks.link.generated-index.title": { + "message": "与框架集成", + "description": "The generated-index page title for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides": { + "message": "指南", + "description": "The label for category 'Guides' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides.link.generated-index.title": { + "message": "指南", + "description": "The generated-index page title for category 'Guides' in sidebar 'docs'" + } +} diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/.sync b/i18n/zh/docusaurus-plugin-content-docs/current/.sync new file mode 100644 index 0000000..0edad02 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/.sync @@ -0,0 +1 @@ +34a2b627cae6efda9e5b5b63191ac878cc868f7e diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md new file mode 100644 index 0000000..9a21511 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md @@ -0,0 +1,82 @@ +--- +sidebar_label: columnShape +title: columnShape 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 columnShape 配置项。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# columnShape + +### 描述 {#description} + +@short: 可选。配置 Pivot 列的外观和行为 + +### 用法 {#usage} + +~~~jsx +columnShape?: { + sort?: boolean, + width?: { + [field: string]: number + }, + autoWidth?: { + columns: { + [field: string]: boolean + }, + auto?: boolean | "header" | "data", + maxRows?: number, + firstOnly?: boolean + } +}; +~~~ + +### 参数 {#parameters} + +- `sort` - (可选)若为 **true**(默认值),则在 UI 中单击列标题时启用排序;若为 **false**,则禁用排序 +- `width` - (可选)定义列的宽度;该对象的每个键为字段 id,值为该列的宽度(单位:像素) +- `autoWidth` - (可选)定义如何自动计算列宽的对象。默认配置使用 20 行,宽度基于标题和数据计算,每个字段只分析一次。该对象的参数如下: + - `columns` - (必填)一个对象,每个键为字段 id,布尔值定义是否自动计算该列的宽度 + - `auto` - (可选)若设为 **header**,则根据标题文本调整宽度;若设为 **data**,则根据内容最宽的单元格调整宽度;若设为 **true**,则同时根据标题和单元格的内容调整宽度。 + 若 autowidth 设为 **false**,则使用 `width` 值,或应用 [`tableShape`](api/config/tableshape-property.md) 属性中 `columnWidth` 的值。 + - `maxRows` - (可选)用于计算 autoWidth 的处理行数 + - `firstOnly` - (可选)若设为 **true**(默认值),则对同一数据的每个字段只分析一次以计算列宽;若同一数据对应多个列(例如 *oil* 字段使用 *count* 操作,以及 *oil* 字段使用 *sum* 操作),则只分析第一列中的数据,其他列继承该宽度 + +## 示例 {#example} + +~~~jsx {18-31} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + autoWidth: { + // 为这些字段计算列宽 + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + auto: true, + // 分析所有字段 + firstOnly: false + } + } +}); +~~~ + +**相关示例**: +- [Pivot 2. 自动宽度:根据内容调整列宽](https://snippet.dhtmlx.com/tn1yw14m) +- [Pivot 2. 设置列宽](https://snippet.dhtmlx.com/ceu34kkn) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/config-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/config-property.md new file mode 100644 index 0000000..780e00b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/config-property.md @@ -0,0 +1,146 @@ +--- +sidebar_label: config +title: config 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 config 配置项的相关信息。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# config + +### 描述 {#description} + +@short: 可选。定义 Pivot 表格的结构以及数据的聚合方式 + +### 用法 {#usage} + +~~~jsx +config?: { + rows?: string | {field: string, method?: string}[], + columns?: string | {field: string, method?: string}[], + values?: string | {field: string, method?: string}[], + filters?: {} +}; +~~~ + +### 参数 {#parameters} + +`config` 参数用于定义哪些字段将作为行和列,以及应对行/列应用哪些额外的数据聚合方法。 + +- `rows` - (可选)定义 Pivot 表格的行。默认值为空数组。可以是代表单个字段 ID 的字符串,也可以是包含字段 ID 和数据提取方法的对象;对象参数如下: + - `field` - (必填)字段的 ID + - `method` - (可选)定义字段数据聚合的方法;时间类数据字段默认提供以下方法:"year"、"quarter"、"month"、"week"、"day"、"hour"、"minute",分别按对应粒度对数据进行分组;此处也可添加自定义方法的名称([参见 `predicates`](api/config/predicates-property.md)),适用于任意数据类型的字段 +- `columns` - (可选)定义 Pivot 表格的列。默认为空数组。可以是单个字段 ID 的字符串,也可以是包含字段 ID 和数据提取方法的对象;对象参数如下: + - `field` - (必填)字段的 ID + - `method` - (可选)定义数据处理方法(适用于时间类数据字段)。 + 默认情况下,**date** 类型的时间类字段支持以下方法:"year"、"quarter"、"month"、"week"、"day"、"hour"、"minute"。此处也可添加自定义方法的名称([参见 `predicates`](api/config/predicates-property.md)),适用于任意数据类型的字段 +- `values` - (可选)定义 Pivot 表格单元格的数据聚合方式。默认为空数组。每个元素可以是表示数据字段 ID 和聚合方法的字符串,也可以是包含字段 ID 和数据聚合方法的对象。对象参数如下: + - `field` - (必填)字段的 ID + - `method` - (必填)定义数据提取方法;有关方法类型及其说明,请参阅[应用方法](guides/working-with-data.md#default-methods) + +
+ +定义 values 的选项 + +您可以使用以下两种等效方式定义 `values`: +- 选项一:表示字段 ID 的字符串 +- 选项二:包含字段 ID 和数据聚合方法的对象 + +### 示例 {#example-values} + +~~~jsx +values: [ + "sum(sales)", // 选项一 + { field: "sales", method: "sum" }, // 选项二 +] +~~~ + +
+ +- `filters` - (可选)定义表格中数据的筛选方式;它是一个包含字段 ID 和筛选规则的对象,默认值为空对象。对象参数如下: + - `field` - (可选)筛选键,即字段的 ID 或带有筛选条件的 ID 数组: + - `equal` - (可选)接受数字、字符串和 Date 值 + - `notEqual` - (可选)接受数字、字符串和 Date 值 + - `greater` - (可选)接受数字和 Date 值 + - `greaterOrEqual` - (可选)接受数字和 Date 值 + - `less` - (可选)接受数字和 Date 值 + - `lessOrEqual` - 接受数字和 Date 值 + - `between` - 包含以下参数的对象: + - `start` - Date + - `end` - Date + - `notBetween` - 包含以下参数的对象: + - `start` - Date + - `end` - Date + - `contains` - 接受字符串值和数字 + - `notContains` - 接受字符串值和数字 + - `beginsWith` - 接受字符串值和数字 + - `notBeginsWith` - 接受字符串值和数字 + - `endsWith` - 接受字符串值和数字 + - `notEndsWith` - 接受字符串值和数字 + - `includes` - (可选)从已筛选的值中指定要显示的值数组;适用于文本和日期值 + +:::info +当 config 被 Pivot 处理后,其属性会接收额外数据。如果您尝试通过 [`api.getState()`](api/internal/getstate-method.md) 方法返回 config 状态,完整对象的形式如下: + +~~~jsx +interface IParsedField { + id: string, + field: string, + method: string | null, + area: 'rows'|'columns'|'values', + base?: string, + label: string, + type: 'number'|'date'|'text' +} + +interface IParsedConfig { + rows: IParsedField[], + columns: IParsedField[], + values: IParsedField[], + filters: { + [field: string]: number | string | [] | + { [operation: string]: number | string | [] | { start:Date, end: Date} } + } +} +~~~ + +参数: + +- `id` - 已处理字段的唯一 id +- `field` - 字段名称 +- `method` - 用于聚合的操作名称。对于行和列,method 是可选参数;若提供,则作为 predicate,定义字段数据在聚合前的预处理方式。对于 values,method 是必填参数。 +- `area` - 字段所属的区域 +- `base` - 用于带有 predicate 的列和行字段。定义原始字段名称,而字段名称则按照 "field_by_predicate" 的模式生成 +- `label` - 文本标签 +- `type` - 数据类型 +::: + +### 示例 {#example} + +~~~jsx {4-26} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // 针对另一个字段("title")的筛选条件 + contains: "A" + } + } + } +}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md new file mode 100644 index 0000000..55cb9ca --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md @@ -0,0 +1,58 @@ +--- +sidebar_label: configPanel +title: configPanel 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 configPanel 配置项。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# configPanel + +### 描述 {#description} + +@short: 可选。控制 UI 中配置面板的显示状态 + +在 UI 中,可通过点击 **Hide Settings** 按钮来隐藏或显示该面板。 + +### 用法 {#usage} + +~~~jsx +configPanel?: boolean; +~~~ + +### 参数 {#parameters} + +该属性可设置为 **true** 或 **false**: + +- `true` - 默认值,显示配置面板 +- `false` - 隐藏配置面板 + +## 示例 {#example} + +~~~jsx {5} +// 初始化时隐藏配置面板 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + configPanel: false, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +**相关示例**: [Pivot 2.0:切换配置面板的显示状态](https://snippet.dhtmlx.com/1xq1x5bo) + +**相关文章**: +- [`show-config-panel` 事件](api/events/show-config-panel-event.md) +- [`showConfigPanel()` 方法](api/methods/showconfigpanel-method.md) +- [控制配置面板的显示状态](guides/configuration.md#controlling-visibility-of-configuration-panel) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/data-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/data-property.md new file mode 100644 index 0000000..00ac883 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/data-property.md @@ -0,0 +1,128 @@ +--- +sidebar_label: data +title: data 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 data 配置项。浏览开发指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# data + +### 描述 {#description} + +@short: 可选。一个对象数组,包含 Pivot 表格的数据 + +### 用法 {#usage} + +~~~jsx +data?: []; +~~~ + +### 参数 {#parameters} + +`data` 数组中的每个对象代表一行数据,默认值为空数组。`data` 属性没有直接的子属性,但数组中的每个对象可以包含任意数量的属性,这些属性将作为 Pivot 表格的维度和值。 + +`data` 数组示例: + +~~~jsx +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + { + name: "Argentina", + year: 2017, + continent: "South America", + form: "Republic", + gdp: 212.507, + oil: 1.732, + balance: 7.167, + when: new Date("1/15/2017") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 260.071, + oil: 2.845, + balance: 6.728, + when: new Date("6/16/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 324.405, + oil: 4.333, + balance: 5.99, + when: new Date("2/20/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 305.763, + oil: 2.626, + balance: 7.544, + when: new Date("8/17/2014") + }, + //其他数据 +]; +~~~ + +### 示例 {#example} + +~~~jsx {3-29} +const table = new pivot.Pivot("#root", { + fields, + data: [ + { + rank: 1, + title: "Shingeki no Kyojin: The Final Season - Kanketsu-hen", + popularity: 609, + genre: "Action", + studio: "MAPPA", + type: "Special", + episodes: 2, + duration: 61, + members: 347875, + score: 9.17, + }, + { + rank: 2, + title: "Fullmetal Alchemist: Brotherhood", + popularity: 3, + genre: "Action", + studio: "Bones", + type: "TV", + episodes: 64, + duration: 24, + members: 3109951, + score: 9.11 + }, + //其他数据对象 + ], + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/fields-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/fields-property.md new file mode 100644 index 0000000..c820fdd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/fields-property.md @@ -0,0 +1,112 @@ +--- +sidebar_label: fields +title: fields 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 fields 配置项。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载免费的 30 天评估版 DHTMLX Pivot。 +--- + +# fields + +### 描述 {#description} + +@short: 可选。包含 Pivot 表格字段对象的数组 + +`fields` 属性在配置对象中控制 widget 如何解析其接收到的数据字段类型,并允许为字段定义排序顺序。 + +### 用法 {#usage} + +~~~jsx +fields?: [{ + id: string, + label?: string, + type: "number" | "date" | "text", + sort?: "asc" | "desc" | ((a: any, b: any) => number), + format?: string | boolean | numberFormatOptions{} +}]; +~~~ + +### 参数 {#parameters} + +默认情况下,如果未设置该属性,widget 将自动分析传入数据并相应地填充 `fields` 对象。 + +`fields` 数组中的每个对象应包含以下属性: + +- `id` - (必填)字段的 ID +- `label` - (可选)在图形界面中显示的字段标签 +- `type` - (必填)字段中的数据类型("number"、"date" 或 "text") +- `sort` - (可选)定义字段的默认排序顺序。接受 "asc"、"desc" 或自定义排序函数 +- `format` - (可选)允许自定义字段中数字和日期的格式;该格式也将在[导出](guides/exporting-data.md)时生效 + - `string` - (可选)日期的格式(默认情况下,Pivot 使用语言环境中的 `dateFormat`) + - `boolean` - (可选)如果设置为 **false**,数字将按原样显示,不进行任何格式化 + - `numberFormatOptions` - (可选)用于格式化数字字段的选项对象;默认情况下,数字最多显示 3 位小数,并对整数部分应用千位分组。 + - `minimumIntegerDigits`(number)- (可选)整数的最小位数(例如,如果该值设置为 2,数字 1 将显示为 "01");默认值为 1; + - `minimumFractionDigits`(number)- (可选)要使用的最小小数位数(例如,如果该值设置为 2,数字 10.5 将显示为 "10.50");默认值为 0; + - `maximumFractionDigits`(number)- (可选)要使用的最大小数位数(例如,如果该值设置为 2,数字 10.3333... 将显示为 "10.33");默认值为 3; + 有关数字位数选项的更多详情,请参阅 [数字位数选项](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumintegerdigits) + - `prefix`(string)- (可选)数字前的字符串,用于货币等附加符号 + - `suffix`(string)- (可选)数字后的字符串,用于货币等附加符号 + +:::info +如果通过 [`tableShape`](api/config/tableshape-property.md) 属性应用了模板,它将覆盖 `format` 设置。 +::: + +### 示例 {#example} + +~~~jsx {2-34} +const table = new pivot.Pivot("#root", { + fields: [ + { + id: "rank", + label: "Rank", + type: "number" + }, + { + id: "title", + label: "Title", + type: "text" + }, + { + id: "genre", + label: "Genre", + type: "text" + }, + { + id: "studio", + label: "Studio", + type: "text" + }, + { + id: "type", + label: "Type", + type: "text" + }, + { + id: "score", + label: "Score", + type: "number" + }, + //其他字段 + ], + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +**相关文章**: + +- [数字格式化](guides/localization.md#number-formatting) +- [为字段应用格式](guides/working-with-data.md#applying-formats-to-fields) + +**相关示例**: [Pivot 2. 定义字段格式](https://snippet.dhtmlx.com/77nc4j8v) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/headershape-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/headershape-property.md new file mode 100644 index 0000000..2a361cf --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/headershape-property.md @@ -0,0 +1,83 @@ +--- +sidebar_label: headerShape +title: headerShape 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 headerShape 配置项。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# headerShape + +### 描述 {#description} + +@short: 可选。配置 Pivot 表格中表头的外观与行为 + +### 用法 {#usage} + +~~~jsx +headerShape?: { + collapsible?: boolean, + vertical?: boolean, + template?: (label: string, field: string, subLabel?: string) => string, + cellStyle?: ( + field: string, + value: any, + area: "rows"|"columns"|"values", + method?: string, + isTotal?: boolean) + => string, +}; +~~~ + +### 参数 {#parameters} + +- `collapsible` - (可选)若设置为 **true**,表格中的维度分组可折叠。默认值为 **false** +- `vertical` - (可选)若设置为 **true**,将所有表头的文字方向从水平改为垂直。默认值为 **false** +- `cellStyle` - (可选)一个为表头单元格应用自定义样式的函数。该函数返回 CSS 类名,并接受以下参数: + - `field` (string) - (必填)表示单元格对应字段名称的字符串。树形列的表头对应的字段为 "" + - `value` (string | number | date) - (必填)单元格的值 + - `area` - (必填)表示单元格所在区域的字符串("rows"、"columns" 或 "values" 区域) + - `method` (string) - (可选)一个字符串,可表示对 "values" 区域字段执行的操作(例如 "sum"、"count" 等),或对 "columns" 区域字段设置的谓词名称 + - `isTotal` - (可选)定义单元格是否属于汇总列 +- `template` - (可选)定义表头文字的格式。默认情况下,作为行字段时显示 `label` 参数的值,作为值字段时显示标签和方法(例如 *Oil(count)*)。该函数接受字段 id、标签以及方法或谓词 id(如有),并返回处理后的值。默认模板如下: +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +## 示例 {#example} + +在以下示例中,**values** 字段的表头将显示标签和方法名称(subLabel),并将结果转换为小写(例如 *profit (sum)*): + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // 自定义表头文字模板 + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // 其他值 + ], + }, + fields, +}); +~~~ + +**相关示例**: +- [Pivot 2. 网格表头中文字的垂直方向](https://snippet.dhtmlx.com/4qroi8ka) +- [Pivot 2. 可折叠列](https://snippet.dhtmlx.com/pt2ljmcm) +- [Pivot 2. 为表格和表头单元格添加自定义 CSS](https://snippet.dhtmlx.com/nfdcs4i2) + +**相关文章**: +- [配置](guides/configuration.md) +- [单元格样式](guides/stylization.md#cell-style) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/limits-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/limits-property.md new file mode 100644 index 0000000..8996cf5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/limits-property.md @@ -0,0 +1,61 @@ +--- +sidebar_label: limits +title: limits 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 limits 配置项。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天试用版本。 +--- + +# limits + +### 描述 {#description} + +@short: 可选。定义最终数据集中行数和列数的最大限制 + +另请参阅 [限制数据](guides/working-with-data.md#limiting-loaded-data)。 + +### 用法 {#usage} + +~~~jsx +limits?: { + rows?: number, + columns?: number, + raws?: number +}; +~~~ + +### 参数 {#parameters} + +以下参数定义了何时中断数据渲染: + +- `rows` - (可选)设置最终数据集中的最大行数;默认值为 10000。 +- `columns` - (可选)设置最终数据集中的最大列数;默认值为 5000。 +- `raws` - (可选)数据分组前源数据的最大行数(用于聚合的原始数据记录);默认值为无穷大。 + +:::note +limits 适用于大型数据集。limits 的值为近似值,并不反映行数和列数的精确值。 +::: + +## 示例 {#example} + +~~~jsx {18} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + ], + }, + limits:{ rows: 25, columns: 4 } +}); +~~~ + +**相关示例**: [Pivot 2. 数据限制](https://snippet.dhtmlx.com/7ryns8oe) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/locale-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/locale-property.md new file mode 100644 index 0000000..e04edeb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/locale-property.md @@ -0,0 +1,51 @@ +--- +sidebar_label: locale +title: locale 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 locale 配置项的相关信息。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# locale + +### 描述 {#description} + +@short: 可选。Pivot 自定义语言包对象 + +### 用法 {#usage} + +~~~jsx +locale?: object; +~~~ + +### 默认配置 {#default-config} + +默认情况下,Pivot 使用[英语](guides/localization.md#default-locale)语言包。您也可以将其设置为自定义语言包。 + +:::tip +如需动态切换当前语言包,可以使用 Pivot 的 [`setLocale()`](api/methods/setlocale-method.md) 方法 +::: + +### 示例 {#example} + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + + locale: pivot.locales.cn, // 初始将设置 "cn" 语言包 + // 其他参数 +}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/methods-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/methods-property.md new file mode 100644 index 0000000..9ece012 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/methods-property.md @@ -0,0 +1,163 @@ +--- +sidebar_label: methods +title: methods 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 methods 配置项。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# methods + +### 描述 {#description} + +@short: 可选。为数据聚合定义自定义数学方法 + +### 用法 {#usage} + +~~~jsx +methods?: { + [method: string]: { + type?: 'number' | 'date' | 'text' | [], + label?: string, + handler?: (values: number[]) => number, + branchMode?: "raw"|"result", + branchMath?: string + } +}; +~~~ + +### 参数 {#parameters} + +每个方法由一个键值对表示,其中 `method` 是方法的名称,值是描述该方法行为的对象。每个对象具有以下参数: + +- `handler` - (自定义方法必填)一个从数字数组中计算聚合值的函数;该函数接收一个值数组作为输入,并返回单个值作为输出 +- `type` - (可选)该方法适用的数据类型;可以是 "number"、"date" 或 "text",或这些值的数组 +- `label` - (可选)在 GUI 中显示的方法标签 +- `branchMode` - (可选)定义树形表格中总计值的计算模式;`branchMode` 可设置为 `raw`,基于所有原始数据进行计算;`result`(默认值)在树形模式下基于已处理的数据进行计算 +- `branchMath` - (可选)在树形模式下用于计算总计值的方法名称;默认与方法名称相同(对于 "max" 方法,`branchMath` 也是 "max") + +默认情况下,`methods` 属性是一个空对象 {},表示未定义任何自定义方法。methods 对象中可定义的子属性数量没有限制。 + +预定义方法: + +~~~jsx +defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +每个方法的定义请参见:[应用方法](guides/working-with-data.md#default-methods) + +## 示例 {#example} + +以下示例展示了如何为 date 类型计算唯一值计数和平均值。**countUnique** 函数接收一个数字数组(values)作为输入,并使用 **reduce** 方法计算唯一值的精确数量。**countunique_date** 子属性包含一个 handler 函数,用于从日期值数组中获取唯一值。**average_date** 子属性包含一个 handler,用于计算日期值数组的平均值。 + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique" + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// 对 "count" 和 "unique count" 结果显示整数 +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// 将日期字符串转换为 Date 对象 +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +**相关示例**: [Pivot 2. 自定义数学方法](https://snippet.dhtmlx.com/lv90d8q2) + +**相关文章**:[应用数学方法](guides/working-with-data.md#applying-maths-methods) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/predicates-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/predicates-property.md new file mode 100644 index 0000000..5bf1727 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/predicates-property.md @@ -0,0 +1,117 @@ +--- +sidebar_label: predicates +title: predicates 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 predicates 配置项。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# predicates + +### 描述 {#description} + +@short: 可选。为数据维度(行、列)提供自定义预处理函数 + +它定义了数据在应用之前应如何被修改。 + +### 用法 {#usage} + +~~~jsx +predicates?: { + [key: string]: { + handler: (value: any) => any, + type: 'number' | 'date' | 'text' | [], + label?: string | (type: 'number' | 'date' | 'text') => string, + template?: (value: any, locale?: any) => string, + field?: (value:string) => boolean, + filter?: { + type: "number"|"text"|"date"|"tuple", + format?:(any) => string + } + } +}; +~~~ + +### 参数 {#parameters} + +该属性是一个对象,其中键为自定义函数的名称,值为包含实际函数定义的对象。predicate 对象可包含多个键值对,所有键值对均可在 Pivot 配置中使用。每个对象具有以下参数: + +- `label` - (可选)predicate 的标签,在 GUI 的下拉菜单中显示于行/列的数据修改选项里 +- `type` - (必填)定义该 predicate 可应用于哪些字段类型;可为 "number"、"date"、"text" 或这些值的数组 +- `field` - (可选)定义指定字段数据处理方式的函数,接收字段 id 作为参数,若该 predicate 应添加到指定字段则返回 **true** +- `filter` - (可选)默认情况下,过滤器类型取自 `type` 参数,但如需使用其他类型,可使用此 `filter` 对象。它包含以下参数: + - `type` - (可选)定义所应用的字段类型:"number"|"text"|"date"|"tuple"。"tuple" 是一种用于数值的组合过滤器(数据按数值过滤,但过滤器中显示文本值) + - `format` - (可选)定义过滤选项显示格式的函数;若未定义 format,则使用 template 参数中的格式;若此处(`filter` 对象)未指定 type,则 format 将应用于 predicate 的 `type` 参数所设置的类型 +- `handler` - (自定义 predicate 必填)定义数据处理方式的函数;该函数应接收单个参数作为待处理的值,并返回处理后的值 +- `template` - (可选)定义数据显示方式的函数;该函数返回处理后的值,接收 `handler` 返回的值,必要时可使用 [`locale`](api/config/locale-property.md) 对文本值进行本地化。 + +若未通过 `predicates` 属性指定 predicate,则应用以下默认 predicate: + +~~~jsx +const defaultPredicates = { + // 表示原始(未处理)值的服务 predicate + $empty: { label: (type) => `Raw ${type}`, type: ["number", "date", "text"] }, + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +## 示例 {#example} + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// 将日期字符串转换为 Date 对象 +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +**相关文章**:[使用 predicate 处理数据](guides/working-with-data.md#processing-data-with-predicates) + +**相关示例**:[Pivot 2. 自定义 predicate](https://snippet.dhtmlx.com/mhymus00) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/readonly-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/readonly-property.md new file mode 100644 index 0000000..53c8f6b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/readonly-property.md @@ -0,0 +1,52 @@ +--- +sidebar_label: readonly +title: readonly 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 readonly 配置项。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# readonly + +### 描述 {#description} + +@short: 可选。启用/禁用只读模式 + +在只读模式下,无法通过 UI 配置 Pivot 的结构。 + +### 用法 {#usage} + +~~~jsx + readonly?: boolean; +~~~ + +### 参数 {#parameters} + +该属性可设置为 **true** 或 **false**: + +- `true` - 启用只读模式 +- `false` - 默认值,禁用只读模式 + +## 示例 {#example} + +~~~jsx {18} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + readonly: true +}); +~~~ + +**相关示例**: [Pivot 2. 只读模式](https://snippet.dhtmlx.com/0k0mvycv) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md new file mode 100644 index 0000000..9bfbc15 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md @@ -0,0 +1,131 @@ +--- +sidebar_label: tableShape +title: tableShape 配置项 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 tableShape 配置项。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天试用版。 +--- + +# tableShape + +### 描述 {#description} + +@short: 可选。配置 Pivot 表格的外观 + +### 用法 {#usage} + +~~~jsx +tableShape?: { + templates?: { + [field: string]: ( + value: any, + operation: string + ) => any; + }, + totalRow?: boolean | "sumOnly", + totalColumn?: boolean | "sumOnly", + marks?: { + [cssClass: string]: ((v: any, columnData: any, rowData: any) => boolean) + | "max" + | "min" + }, + sizes?: { + rowHeight?: number, + headerHeight?: number, + columnWidth?: number, + footerHeight?: number + }, + tree?:boolean, + cleanRows?: boolean, + split?: { + left?: boolean, + right?: boolean, + }, + cellStyle?: ( + field: string, + value: any, + area: "rows"|"columns"|"values", + method?: string, + isTotal?: "row"|"column"|"both") + => string, +}; +~~~ + +### 参数 {#parameters} + +- `templates` - (可选)允许为单元格设置模板;它是一个对象,其中: + - 每个键是字段 id + - 值是一个函数,该函数返回字符串并接收单元格的值和操作类型。基于指定字段的所有列都将应用对应的模板。例如,可以设置计量单位,或对数值返回指定小数位数等。详见下方示例。 +- `marks` - (可选)允许为满足条件的单元格标记样式。它是一个对象,键为 CSS 类名,值为函数或预定义字符串("max"、"min")之一。函数应为被检查的值返回布尔值,若返回 **true**,则将该 CSS 类应用到单元格上。更多信息及示例请参阅 [单元格样式](guides/stylization.md#cell-style)。 +- `sizes` - (可选)定义表格的以下尺寸参数: + - `rowHeight` - (可选)Pivot 表格中行的高度,单位为像素,默认值为 34 + - `headerHeight` - (可选)表头高度,单位为像素,默认值为 30 + - `footerHeight` - (可选)表尾高度,单位为像素,默认值为 30 + - `columnWidth` - (可选)列宽度,单位为像素,默认值为 150 +- `cellStyle` - (可选)为单元格应用自定义样式的函数。该函数包含以下参数: + - `field` - (必填)表示所应用样式的字段名的字符串 + - `value` - (必填)单元格的值(该行列对应的实际数据) + - `area` - (必填)指示单元格所在表格区域的字符串("rows"、"columns" 或 "values" 区域) + - `method` - (可选)表示单元格所执行操作的字符串(如 "sum"、"count" 等) + - `isTotal` - (可选)定义单元格是否属于总计行、总计列或两者兼属:"row"|"column"|"both" + `cellStyle` 函数返回一个字符串,可作为 CSS 类名用于为单元格应用特定样式。 +- `tree` - (可选)若设为 **true**,则启用树形模式,数据将以可展开的行形式呈现,默认值为 **false**。更多信息及示例请参阅 [切换到树形模式](guides/configuration.md#enabling-the-tree-mode) +- `totalColumn` - (可选)若为 **true**,则启用总计列,显示各行的汇总值(默认值为 **false**)。若值设为 "sumOnly",则仅生成包含总和值的列(仅适用于求和操作) +- `totalRow` - (可选)若为 **true**,则启用总计行,在表尾显示汇总值(默认值为 **false**)。若值设为 "sumOnly",则仅生成包含总计值的行(仅适用于求和操作) +- `cleanRows` - (可选)若设为 **true**,则在表格视图中隐藏比例列中的重复值,默认值为 **false** +- `split` - (可选)根据指定参数冻结左侧或右侧的列(参阅 [冻结列](guides/configuration.md#freezing-columns)): + - `left`(boolean)- 若设为 **true**(默认值为 **false**),则固定左侧列,使列在滚动时保持静止可见。被固定的列数等于 [`config`](api/config/config-property.md) 属性中定义的行字段数量 + - `right`(boolean)- 在右侧固定总计列,默认值为 **false** + +默认情况下,`tableShape` 为 undefined,即不显示总计行和总计列,不应用任何模板和标记,数据以普通表格形式展示(而非树形),且列在滚动时不会固定。 + +## 示例 {#example} + +在以下示例中,我们对 *state* 单元格应用模板,以显示州的完整名称与缩写的组合。 + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", +// 其他值, +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // 设置模板以自定义 "state" 单元格的值 + state: v => v+ ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // 其他值 + ], + }, + fields, +}); +~~~ + +**相关示例**: + +- [Pivot 2. 树形模式](https://snippet.dhtmlx.com/6ylkoukn) +- [Pivot 2. 冻结(固定)列](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. 设置行高、表头高、表尾高及所有列宽](https://snippet.dhtmlx.com/x46uyfy9) +- [Pivot 2. 清除重复行](https://snippet.dhtmlx.com/rwwhgv2w?tag=pivot) +- [Pivot 2. 为表格和表头单元格添加自定义 CSS](https://snippet.dhtmlx.com/nfdcs4i2) + +**相关文章**: +- [配置](guides/configuration.md) +- [单元格样式](guides/stylization.md#cell-style) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/add-field-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/add-field-event.md new file mode 100644 index 0000000..167bf2b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/add-field-event.md @@ -0,0 +1,74 @@ +--- +sidebar_label: add-field +title: add-field 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 add-field 事件。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# add-field + +### 描述 {#description} + +@short: 当新字段添加到行、列或值区域时触发 + +### 用法 {#usage} + +~~~jsx +"add-field": ({ + id?: string | number, + area: string, + field: string | number, + method?: string +}) => boolean; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接收一个包含以下参数的对象: + +- `id` - (可选)新字段的指定 id;如果未设置,则使用自动生成的 id +- `area` - (必填)添加新字段的区域名称,可以是 "rows"、"columns" 或 "values" 区域 +- `field` - (必填)字段名称 +- `method` - (可选)定义数据聚合的方法(如果未指定,则使用适合该数据类型的第一个方法);方法可以是以下之一: + - 对于 **values** 区域为必填项,是一个包含数据操作类型的字符串:[默认方法](guides/working-with-data.md#default-methods) + - 对于 **rows** 和 **columns** 区域为可选项,如果设置了值则为谓词;可以是自定义谓词,也可以是默认值之一:"year"、"quarter"、"month"、"week"、"day"、"hour"、"minute"。默认情况下使用原始值。 + 如果设置了自定义谓词或方法,应为 [predicates](api/config/predicates-property.md) 或 [methods](api/config/methods-property.md) 属性指定 id。 + +:::info +如需处理内部事件,可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 示例 {#example} + +以下示例中,我们使用 [`api.intercept()`](api/internal/intercept-method.md) 方法为 **number** 数据类型的值字段添加新方法: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//使用预定义方法添加值 +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "min"; + } +}); +~~~ + +**相关文章**:[api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md new file mode 100644 index 0000000..651c0f4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: apply-filter +title: apply-filter 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 apply-filter 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# apply-filter + +### 描述 {#description} + +@short: 在筛选器被应用时触发 + +### 用法 {#usage} + +~~~jsx +"apply-filter": ({ + rule: {} +}) => boolean | void; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接收一个包含以下参数的对象: + +- `rule` - 任意筛选器配置对象,包含如下参数: + - `field` - (必填)要应用筛选器的字段 id + - `filter` - (必填)筛选器类型: + - 文本值:equal、notEqual、contains、notContains、beginsWith、notBeginsWith、endsWith、notEndsWith + - 数值:greater、less、greaterOrEqual、lessOrEqual、equal、notEqual、contains、notContains + - 日期类型:greater、less、greaterOrEqual、lessOrEqual、equal、notEqual、between、notBetween + - `value` - (可选)用于筛选的值 + - `includes` - (可选)一个值数组,用于从已筛选的结果中指定要显示的值;适用于文本和日期类型的值 + +:::info +如需处理内部事件,可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 示例 {#example} + +~~~jsx {20-23} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//将应用筛选器的字段标签输出到控制台 +table.api.on("apply-filter", (ev) => { + console.log("The field to which filter was applied:", ev.rule.field); +}); +~~~ + +**相关文章**:[api.on()](api/internal/on-method.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md new file mode 100644 index 0000000..5a5248a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md @@ -0,0 +1,82 @@ +--- +sidebar_label: delete-field +title: delete-field 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 delete-field 事件。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# delete-field + +### 描述 {#description} + +@short: 移除字段时触发 + +### 用法 {#usage} + +~~~jsx +"delete-field": ({ + area: string, + id: string | number +}) => boolean | void; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接收一个包含以下参数的对象: + +- `area` - (必填)移除字段所在区域的名称,可以是 "rows"、"columns" 或 "values" 区域 +- `id` - (必填)被移除字段的 id + +:::info +处理内部事件可使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 示例 {#example} + +在以下示例中,`delete-field` 操作通过 [`api.exec()`](api/internal/exec-method.md) 方法触发。最后一个字段将从 **values** 区域中移除。[`api.getState()`](api/internal/getstate-method.md) 方法用于获取 Pivot [`config`](api/config/config-property.md) 的当前状态。点击按钮将触发该操作。 + +~~~jsx {31-34} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//调用 API 方法:从 config 的 values 中移除指定值 +function removeLastField() { + if (table.api) { + const state = table.api.getState(); + const config = state.config; + + const count = config.values.length; + + if (count) { + const lastValue = config.values[count - 1]; + + table.api.exec("delete-field", { + area: "values", + id: lastValue.id, // 自动生成的 config.values 中条目的 ID + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/move-field-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/move-field-event.md new file mode 100644 index 0000000..4677eb4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/move-field-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: move-field +title: move-field 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 move-field 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# move-field + +### 描述 {#description} + +@short: 当字段重新排序时触发 + +### 用法 {#usage} + +~~~jsx +"move-field": ({ + area: string, + id: string | number, + before?: string, + after?: string +}) => void | boolean; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接受一个包含以下参数的对象: + +- `area` - (必填)发生重新排序的区域名称,可以是 "rows"、"columns" 或 "values" 区域 +- `id` - (必填)被移动字段的 id +- `before` - (可选)移动字段被放置到其之前的字段 id +- `after` - (可选)移动字段被放置到其之后的字段 id + +:::info +处理内部 events 时,您可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 示例 {#example} + +~~~jsx {20-23} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//将重新排序字段的 id 输出到控制台 +table.api.on("move-field", (ev) => { + console.log("The id of the reordered field:", ev.id); +}); +~~~ + +**相关文章**:[api.on()](api/internal/on-method.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md new file mode 100644 index 0000000..800591d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md @@ -0,0 +1,95 @@ +--- +sidebar_label: open-filter +title: open-filter 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 open-filter 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# open-filter + +### 描述 {#description} + +@short: 当字段的过滤器被激活时触发 + +### 用法 {#usage} + +~~~jsx +"open-filter": ({ + id: string | null, + area?: "values" | "rows" | "columns" +}) => boolean | void; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接受以下参数: + +- `area` - 字段所在的区域("rows"、"columns"、"values") +- `id` - 字段的 id;如果只传入一个值为 null 的 `id` 参数,则过滤器将被关闭。 + +:::info +如需处理内部事件,可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 返回值 {#returns} + +该函数可以返回布尔值或 void。当返回 **false** 时,相应的事件操作将被中止。 + +### 示例 {#example} + +以下示例展示了如何在关闭过滤框时隐藏配置面板: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + if(!ev.id) { + table.api.exec("show-config-panel", { + mode: false + }); + } +}); +~~~ + +以下示例将激活过滤器的字段 id 输出到控制台: + +~~~jsx {20-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + console.log("The field id for which filter is activated:", ev.id); +}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/render-table-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/render-table-event.md new file mode 100644 index 0000000..3c1b527 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/render-table-event.md @@ -0,0 +1,178 @@ +--- +sidebar_label: render-table +title: render-table 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 render-table 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 30 天免费评估版本。 +--- + +# render-table + +### 描述 {#description} + +@short: 在处理完 widget 配置之后、渲染表格之前触发 + +该事件允许您动态修改最终的表格配置,或完全阻止表格的渲染。 + +### 用法 {#usage} + +~~~jsx +"render-table": ({ + config: { + columns?: any[], + data?: any[], + footer?: boolean, + sizes?: { + rowHeight?: number, + headerHeight?: number, + columnWidth?: number, + footerHeight?: number + }, + split?: { + left?: number; + right?: number; + }, + tree?: boolean, + cellStyle?: (row: any, col: any) => string, + } +}) => boolean | void; +~~~ + +### 参数 {#parameters} + +该动作的回调函数接收包含以下参数的 `config` 对象: + +- `columns` - (可选)列数组,每个对象包含以下参数: + - `id` (number) - (必填)列的 id + - `cell` (any) - (可选)包含单元格内容的模板(请参阅[通过 template 辅助函数添加模板](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (可选)通过 [`tableShape`](api/config/tableshape-property.md) 属性定义的模板 + - `fields` (array) - (可选)在树模式下定义层级列中的字段,反映该列在不同层级上显示的字段 + - `field` - (可选)字段 id 字符串 + - `method` (string) - (可选)为该列中某个字段定义的方法 + - `methods` (array) - (可选)定义在树模式下层级列中字段所应用的方法 + - `format` (string 或 object) - (必填)日期格式或数字格式(参阅[对字段应用格式](guides/working-with-data.md#applying-formats-to-fields)) + - `isNumeric` (boolean) - (可选)定义列是否包含数值 + - `isTotal` (boolean) - (可选)定义是否为汇总列 + - `area` (string) - (可选)列渲染所在的区域:"rows"、"columns"、"values" + - `header` - (可选)表头单元格数组,每个单元格包含以下属性: + - `text` (string) - (可选)单元格文本、格式化值或经谓词模板处理的值 + - `rowspan` (number) - (可选)表头跨越的行数 + - `colspan` (number) - (可选)表头跨越的列数 + - `value` (any) - (必填)原始值,适用于属于 "columns" 区域的单元格 + - `field` (string) - (必填)显示值的字段,适用于属于 "columns" 区域的单元格 + - `method` (string) - (必填)字段谓词,适用于属于 "columns" 区域且定义了谓词的单元格 + - `format` (string 或 object) - 日期格式或数字格式(参阅[对字段应用格式](guides/working-with-data.md#applying-formats-to-fields)) + - `footer` - (可选)表尾标签或与表头设置相同的表尾设置对象 + - `data` - (可选)表格数据对象数组,每个对象代表一行: + - `id` (number) - (必填)行 id + - `values` (array) - (必填)包含行数据的数组 + - `open` (boolean) - (可选)分支展开状态 + - `$level` (boolean) - (可选)分支索引 +- `footer` - (可选)设置为 **true** 时,在表格底部显示表尾;默认设置为 **false** 且不可见 +- `sizes` - (可选)包含表格尺寸设置的对象,具体包括 columnWidth、footerHeight、headerHeight、rowHeight +- `split` (object) - (可选)包含以下属性的对象: + - `left` (number) - 从左侧固定的列数 + - `right` (number) - 从右侧固定的列数 +- `tree` - (可选)定义是否启用树模式(启用时为 **true**) +- `cellStyle` - (可选)为单元格应用自定义样式的函数,接收行对象和列对象,返回 CSS 类名字符串:`(row, col) => string` + +:::info +如需处理内部事件,可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 返回值 {#returns} + +回调函数可返回 boolean 或 void。 +若事件处理函数返回 **false**,将阻止相关操作。在此情况下,将阻止表格的渲染。 + +### 示例 {#example} + +以下示例展示如何将 [`config`](api/config/config-property.md) 对象输出到控制台并添加表尾。 + +~~~jsx {20-28} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.intercept("render-table", (ev) => { + console.log(ev.config); //输出 config 对象 + console.log(ev.config.columns); //输出 columns 数组 + + ev.config.footer = true; + ev.config.columns[0].footer = ["Custom footer"]; + + // 在此处返回 "false" 将阻止表格渲染 +}); +~~~ + +以下示例展示如何通过按钮点击展开/折叠所有行。树模式需通过 [`tableShape`](api/config/tableshape-property.md) 属性启用。 + +~~~jsx +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true, + }, + fields, + data: dataset, + config: { + rows: ["type", "studio"], + columns: [], + values: [ + { + field: "score", + method: "max" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + }, + { + field: "episodes", + method: "count" + } + ] + } +}); + +const api = table.api; +const tableApi = api.getTable(); + +// 在表格配置更新时关闭所有分支 +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // 在此处返回 "false" 将阻止表格渲染 + // return false; +}); + +function openAll() { + tableApi.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableApi.exec("close-row", { id: 0, nested: true }); +} +~~~ + +另请参阅如何使用 `render-table` 事件配置拆分功能:[冻结列](guides/configuration.md#freezing-columns)。 + +**相关文章**: [pivot.template 辅助函数](api/helpers/template.md) + +**相关示例**: [Pivot 2. 自定义冻结(固定)列(自定义数量)](https://snippet.dhtmlx.com/53erlmgp) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md new file mode 100644 index 0000000..34e099d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md @@ -0,0 +1,60 @@ +--- +sidebar_label: show-config-panel +title: show-config-panel 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 show-config-panel 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# show-config-panel + +### 描述 {#description} + +@short: 当配置面板的可见性发生变化时触发 + +### 用法 {#usage} + +~~~jsx +"show-config-panel": ({ + mode: boolean +}) +~~~ + +### 参数 {#parameters} + +该操作的回调函数接收一个包含以下参数的对象: + +- `mode` - (必填)如果值设为 **true**(默认值),则显示配置面板;设为 **false** 时隐藏配置面板 + +:::info +处理内部事件可使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 示例 {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//隐藏配置面板 +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +**相关文章**: +- [`showConfigPanel()` 方法](api/methods/showconfigpanel-method.md) +- [`configPanel` 属性](api/config/configpanel-property.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/update-config-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/update-config-event.md new file mode 100644 index 0000000..c86f3f8 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/update-config-event.md @@ -0,0 +1,78 @@ +--- +sidebar_label: update-config +title: update-config 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 update-config 事件。浏览开发者指南和 API 参考文档,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# update-config + +### 描述 {#description} + +@short: 通过 Pivot UI 修改行、列或聚合函数时触发 + +该操作可用于保存用户的聚合配置,以便在下次使用 widget 时应用该配置,使用户能够从上次离开的地方继续操作。 + +### 用法 {#usage} + +~~~jsx +"update-config": ({ + rows: string[], + columns: string[], + values: [], + filters: {} +}) => boolean | void; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接收一个包含已处理的 [`config`](api/config/config-property.md) 参数的对象: + +- `rows` - Pivot 表格的行。一个包含字段 ID 和数据提取方法的对象;对象参数如下: + - `field` - 字段的 ID + - `method` - 数据提取方法(适用于基于时间的数据字段) +- `columns` - 定义 Pivot 表格的列。一个包含字段 ID 和数据提取方法的对象;对象参数如下: + - `field` - 字段的 ID + - `method` - 定义数据提取方法(适用于基于时间的数据字段)。 + 默认情况下,方法适用于基于时间的字段(**date** 类型),可选值为:"year"、"quarter"、"month"、"week"、"day"、"hour"、"minute" +- `values` - 定义 Pivot 表格单元格的数据聚合。一个包含字段 ID 和数据聚合方法的对象,对象参数如下: + - `field` - 字段的 ID + - `method` - 定义数据提取方法;关于方法及可选项,请参阅[应用方法](guides/working-with-data.md#default-methods) +- `filters` - (可选)定义表格中数据的过滤方式;一个包含字段 ID 和数据聚合方法的对象。`filter` 对象的说明请参见:[`config`](api/config/config-property.md) + +:::info +处理内部事件时,您可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 返回值 {#returns} + +回调函数可返回布尔值或 void。 +如果事件处理函数返回 *false*,则触发该事件的操作将被阻止,`update-config` 操作将停止执行。 + +### 示例 {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//将 config 对象输出到控制台 +table.api.on("update-config", (config) => { + console.log("Config has changed", config); +}); +~~~ + +**相关文章**:[api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/events/update-field-event.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/update-field-event.md new file mode 100644 index 0000000..2ab1629 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/events/update-field-event.md @@ -0,0 +1,67 @@ +--- +sidebar_label: update-field +title: update-field 事件 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 update-field 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# update-field + +### 描述 {#description} + +@short: 在更新字段时触发 + +### 用法 {#usage} + +~~~jsx +"update-field": ({ + id: string | number, + method: string, + area: string +}) => boolean; +~~~ + +### 参数 {#parameters} + +该操作的回调函数接收一个包含以下参数的对象: + +- `id` - (必填)被更新字段的 id +- `method` - (必填)方法可以是以下值之一: + - 对于 **values** 区域,为包含某种数据操作类型的字符串:[默认方法](guides/working-with-data.md#default-methods) + - 对于 **rows** 和 **columns** 区域,可以是数据谓词值,取以下值之一:"year"、"quarter"、"month"、"week"、"day"、"hour"、"minute"。默认情况下使用原始值。 + 如果设置了自定义谓词或方法,则应在 [predicate](api/config/predicates-property.md) 或 [methods](api/config/methods-property.md) 属性中指定 id。 +- `area` - (必填)字段所在区域的名称,可以是 "rows"、"columns" 或 "values" 区域 + +:::info +要处理内部事件,可以使用 [Event Bus 方法](api/overview/internal-eventbus-overview.md) +::: + +### 示例 {#example} + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +//将被更新字段的 id 输出到控制台 +table.api.on("update-field", (ev) => { + console.log("The id of the field that was updated:", ev.id); +}); +~~~ + +**相关文章**: +- [api.on()](api/internal/on-method.md) +- [methods](api/config/methods-property.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/helpers/template.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/helpers/template.md new file mode 100644 index 0000000..c2bbf50 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/helpers/template.md @@ -0,0 +1,89 @@ +--- +sidebar_label: template +title: template +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 Pivot template 辅助函数。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +### 描述 {#description} + +`template` 函数用于为表格的表头单元格和主体单元格应用模板。 + +### 用法 {#usage} + +用于主体单元格: + +~~~jsx +pivot.template({value, method, row, column}) => string; +~~~ + +用于表头单元格: + +~~~jsx +pivot.template({value, field, method, cell, column}) => string; +~~~ + +### 参数 {#parameters} + +主体单元格的函数接受以下参数: + +- `value` (any) - (必填)单元格原始值 +- `method` (string) - (必填)用于该列的方法或谓词 +- `row` - (必填)包含行数据的对象: + - `id` (number) - (必填)行 id + - `values` (array) - (必填)包含行数据的数组 + - `open` (boolean) - (可选)分支展开状态 + - `$level` (boolean) - (可选)分支层级索引 +- `column` - (必填)包含列数据的对象: + - `id` (number) - (必填)列的 id + - `cell` (any) - (可选)包含单元格内容的模板(请参阅[通过 template 辅助函数添加模板](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (可选)通过 [`tableShape`](api/config/tableshape-property.md) 属性定义的模板 + - `fields` (array) - (可选)在树形模式下定义层次列中的字段,反映该列在不同层级上显示的字段 + - `field` - (可选)字段 id 字符串 + - `method` (string) - (可选)为该列中某字段定义的方法 + - `methods` (array) - (可选)定义在树形模式下应用于层次列中各字段的方法 + - `format` (string or object) - (必填)日期格式或数字格式(请参阅[为字段应用格式](guides/working-with-data.md#applying-formats-to-fields)) + - `isNumeric` (boolean) - (可选)定义该列是否包含数值 + - `isTotal` (boolean) - (可选)定义该列是否为汇总列 + - `area` (string) - (可选)列所在的区域:"rows"、"columns"、"values" + - `header` - (可选)表头单元格数组,每个单元格具有以下属性: + - `text` (string) - (可选)单元格文本、格式化值或经谓词模板处理后的值 + - `rowspan` (number) - (可选)表头跨越的行数 + - `colspan` (number) - (可选)表头跨越的列数 + - `value` (any) - (必填)原始值,当单元格属于 "columns" 区域时使用 + - `field` (string) - (必填)所显示值对应的字段,当单元格属于 "columns" 区域时使用 + - `method` (string) - (必填)字段谓词,当单元格属于 "columns" 区域且定义了谓词时使用 + - `format` (string or object) - 日期格式或数字格式(请参阅[为字段应用格式](guides/working-with-data.md#applying-formats-to-fields)) + +表头单元格的函数参数如下: + +- `value` (any) - (必填)单元格原始值 +- `method` (string) - (可选)用于该列的谓词 +- `field` (string) - (可选)在单元格中显示值的字段 +- `cell` - (必填)包含单元格数据的对象: + - `text` (string) - (可选)单元格文本、格式化值或经谓词模板处理后的值 + - `rowspan` (number) - (可选)表头跨越的行数 + - `colspan` (number) - (可选)表头跨越的列数 + - `value` (any) - (必填)原始值,当单元格属于 "columns" 区域时使用 + - `field` (string) - (必填)所显示值对应的字段,当单元格属于 "columns" 区域时使用 + - `method` (string) - (必填)字段谓词,当单元格属于 "columns" 区域且定义了谓词时使用 + - `format` (string or object) - (必填)日期格式或数字格式(请参阅[为字段应用格式](guides/working-with-data.md#applying-formats-to-fields)) +- `column` - (必填)包含列数据的对象(与主体单元格相同) + +### 示例 {#example} + +以下代码片段演示了如何通过 `pivot.template` 辅助函数定义模板。该辅助函数在表格渲染前生效,通过使用 [api.intercept()](api/internal/intercept-method.md) 方法拦截 [render-table](api/events/render-table-event.md) 事件来实现。 + +该代码片段展示了如何为以下内容添加图标: + +- 基于字段(id、user_score)的主体单元格(模板添加旗帜和星形图标) +- 基于字段名称的表头标签(例如,若字段为 "id",则在表头值旁添加地球图标) +- 基于值的列表头(添加彩色箭头指示器) + + + + +**相关文章**: + +- [`render-table`](api/events/render-table-event.md) +- [为单元格应用模板](guides/configuration.md#applying-templates-to-cells) +- [为表头应用模板](guides/configuration.md#applying-templates-to-headers) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/detach-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/detach-method.md new file mode 100644 index 0000000..5d36a0d --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/detach-method.md @@ -0,0 +1,69 @@ +--- +sidebar_label: api.detach() +title: detach 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 detach 方法。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# api.detach() + +## 描述 {#description} + +@short: 用于移除/解绑动作处理器 + +## 用法 {#usage} + +~~~jsx +api.detach(tag: number | string ): void; +~~~ + +## 参数 {#parameters} + +- `tag` - 动作标签的名称 + +### 示例 {#example} + +在下面的示例中,我们向 [`api.on()`](api/internal/on-method.md) 处理器添加一个包含 **tag** 属性的对象,然后使用 `api.detach()` 方法停止记录 [`open-filter`](api/events/open-filter-event.md) 动作。 + +~~~jsx {31-34} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 添加处理器 +if (table.api) { + table.api.on( + "open-filter", + ({ area }) => { + console.log("Opened: " + area); + }, + { tag: "track" } + ); +} + +// 解绑处理器 +function stop() { + table.api.detach("track"); +} + +const button = document.createElement("button"); + +button.addEventListener("click", stop); +button.textContent = "Stop logging"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/exec-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/exec-method.md new file mode 100644 index 0000000..5d20768 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/exec-method.md @@ -0,0 +1,83 @@ +--- +sidebar_label: api.exec() +title: exec 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 exec 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# api.exec() + +### 描述 {#description} + +@short: 允许触发内部事件 + +## 用法 {#usage} + +~~~jsx +api.exec( + event: string, + config: object +): Promise; +~~~ + +## 参数 {#parameters} + +- `event` - (必填)要触发的事件 +- `config` - (必填)包含参数的配置对象(参见要触发的事件) + +## 操作 {#actions} + +:::info +Pivot 事件的完整列表可在[**此处**](api/overview/events-overview.md)查看 +::: + +## 示例 {#example} + +在下面的示例中,[`delete-field`](api/events/delete-field-event.md) 事件通过 `api.exec()` 方法触发。最后一个字段将从 **values** 区域中移除。[`api.getState()`](api/internal/getstate-method.md) 方法用于获取 Pivot [`config`](api/config/config-property.md) 的当前状态。点击按钮后将触发该事件。 + +~~~jsx {32-35} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 调用 API 方法:从 config 的 values 中移除指定值 +function removeLastField() { + if (table.api) { + const state = table.api.getState(); + const config = state.config; + + const count = config.values.length; + + if (count) { + const lastValue = config.values[count - 1]; + + table.api.exec("delete-field", { + area: "values", + id: lastValue.id, // 自动生成的 config.values 中已添加项目的 ID + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md new file mode 100644 index 0000000..011cef3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md @@ -0,0 +1,71 @@ +--- +sidebar_label: api.getReactiveState() +title: getReactiveState 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 getReactiveState 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# api.getReactiveState() + +### 描述 {#description} + +@short: 获取包含 Pivot 响应式属性的对象 + +### 用法 {#usage} + +~~~jsx +api.getReactiveState(): object; +~~~ + +### 返回值 {#returns} + +该方法返回一个包含以下参数的对象: + +~~~jsx +{ + config: {}, // 当前配置(rows、columns、values、filters) + activeFilter: {}, // 活动过滤器对象(若有过滤器处于打开状态) + columnShape: {}, // pivot 列配置 + data: [], // 源数据 + fields: [], // 字段数组 + filters: {}, // 过滤规则 + headerShape: {}, // 表头设置 + predicates: {}, // 各字段可用的断言 + limits: {}, // 数据集中行数和列数的最大限制 + methods: {}, // 数据聚合方法 + tableShape: {}, // 表格设置(尺寸、合计行、模板) + tableConfig: {}, // 表格配置设置(列、数据、尺寸、树形模式、页脚) + configPanel: boolean, // 配置面板的可见状态 + readonly: boolean, // 是否启用只读模式 +} +~~~ + +### 示例 {#example} + +~~~jsx {21-26} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 订阅响应式 config store,并在每次变更时输出日志 +const state = table.api.getReactiveState(); + +state.config.subscribe((config) => { + console.log("Pivot config changed. Its current state:", config); +}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md new file mode 100644 index 0000000..bc9602b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md @@ -0,0 +1,67 @@ +--- +sidebar_label: api.getState() +title: getState 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 getState 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# api.getState() + +### 描述 {#description} + +@short: 获取包含 Pivot 的 StateStore 属性的对象 + +### 用法 {#usage} + +~~~jsx +api.getState(): object; +~~~ + +### 返回值 {#returns} + +该方法返回一个包含以下参数的对象: + +~~~jsx +{ + config: {}, // 当前配置(rows、columns、values、filters) + activeFilter: {}, // 活动过滤器对象(如果有过滤器处于打开状态) + columnShape: {}, // 透视列配置 + data: [], // 源数据 + fields: [], // 字段数组 + filters: {}, // 过滤规则 + headerShape: {}, // 表头设置 + predicates: {}, // 各字段可用的断言 + limits: {}, // 数据集中行和列数量的最大限制 + methods: {}, // 数据聚合方法 + tableShape: {}, // 表格设置(尺寸、合计行、模板) + tableConfig: {}, // 表格配置设置(列、数据、尺寸、树形模式、页脚) + configPanel: boolean, // 配置面板的可见状态 + readonly: boolean, // 是否启用只读模式 +} +~~~ + +### 示例 {#example} + +~~~jsx {21-22} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +const { config } = table.api.getState(); +console.log(config); //将 config 状态输出到控制台 +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md new file mode 100644 index 0000000..3a2edfa --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md @@ -0,0 +1,54 @@ +--- +sidebar_label: api.getStores() +title: getStores 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 getStores 方法。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# api.getStores() + +### 描述 {#description} + +@short: 获取包含 Pivot 的 DataStore 属性的对象 + +### 用法 {#usage} + +~~~jsx +api.getStores(): object; +~~~ + +### 返回值 {#returns} + +该方法返回一个包含 **DataStore** 参数的对象: + +~~~jsx +{ + data: DataStore // (参数对象) +} +~~~ + +### 示例 {#example} + +~~~jsx {21-22} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +const stores = table.api.getStores(); +console.log("DataStore:", stores); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md new file mode 100644 index 0000000..aa48c5c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md @@ -0,0 +1,68 @@ +--- +sidebar_label: api.intercept() +title: intercept 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 intercept 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# api.intercept() + +### 描述 {#description} + +@short: 用于拦截并阻止内部事件 + +### 用法 {#usage} + +~~~jsx +api.intercept( + event: string, + callback: function, + config?: { tag?: number | string | symbol } +): void; +~~~ + +### 参数 {#parameters} + +- `event` - (必填)要触发的事件 +- `callback` - (必填)要执行的回调函数(回调参数取决于所触发的事件) +- `config` - (可选)存储以下参数的对象: + - `tag` - (可选)操作标签。您可以使用标签名称通过 [`detach`](api/internal/detach-method.md) 方法移除操作处理器 + +### 事件 {#events} + +:::info +Pivot 内部事件的完整列表可在[**此处**](api/overview/main-overview.md#pivot-events)查看。 +如果您只想监听操作而不修改,请使用 [`api.on()`](api/internal/on-method.md) 方法。若要对操作进行修改,请使用 `api.intercept()` 方法。 +::: + +### 示例 {#example} + +以下示例展示了如何在初始化时关闭所有可折叠行。 + +~~~jsx {21-24} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 在初始化时关闭所有行 +table.api.intercept("render-table", (ev) => { + ev.config.data.forEach((row) => (row.open = false)); +}, {tag: "render-table-tag"}); +~~~ + +**相关文章**:[`render-table`](api/events/render-table-event.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/on-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/on-method.md new file mode 100644 index 0000000..0dd1f71 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/on-method.md @@ -0,0 +1,72 @@ +--- +sidebar_label: api.on() +title: on 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 on 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# api.on() + +### 描述 {#description} + +@short: 允许为内部事件附加处理函数 + +### 用法 {#usage} + +~~~jsx +api.on( + event: string, + handler: function, + config?: { intercept?: boolean, tag?: number | string | symbol } +): void; +~~~ + +### 参数 {#parameters} + +- `event` - (必填)要触发的事件 +- `handler` - (必填)要附加的处理函数(处理函数的参数取决于所触发的事件) +- `config` - (可选)存储以下参数的对象: + - `intercept` - (可选)如果在创建事件监听器时设置 `intercept: true`,则该事件监听器将在所有其他监听器之前执行 + - `tag` - (可选)操作标签。您可以使用标签名称通过 [`detach`](api/internal/detach-method.md) 方法移除操作处理函数 + +### 事件 {#events} + +:::info +Pivot 内部事件的完整列表可在[**此处**](api/overview/main-overview.md#pivot-events)查看。 +如果您只想监听操作而不对其进行修改,请使用 `api.on()` 方法。若要对操作进行更改,请使用 [`api.intercept()`](api/internal/intercept-method.md) 方法。 +::: + +### 示例 {#example} + +以下示例演示如何输出激活过滤器的字段标签: + +~~~jsx {21-29} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.on("open-filter", (ev) => { + if (ev.id) { + const { config } = table.api.getState(); + const fieldObj = config[ev.area].find((f) => f.id === ev.id); + if (fieldObj) { + console.log("The field for which filter was activated:", fieldObj.label); + } + } +}, {tag: "open-filter-tag"}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md new file mode 100644 index 0000000..c237ab2 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md @@ -0,0 +1,45 @@ +--- +sidebar_label: api.setNext() +title: setNext 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 setNext 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# api.setNext() + +### 描述 {#description} + +@short: 用于将某个操作添加到 Event Bus 的执行顺序中 + +### 用法 {#usage} + +~~~jsx +api.setNext(next: any): void; +~~~ + +### 参数 {#parameters} + +- `next` - (必填)要加入 **Event Bus** 执行顺序的操作 + +### 示例 {#example} + +以下示例展示了如何使用 `api.setNext()` 方法将自定义类集成到 Event Bus 的执行顺序中: + +~~~jsx {13-14} +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +// 假设您有一个名为 someServerService 的自定义服务器服务类 +const someServerService = new ServerDataService(server); + +Promise.all([ + fetch(server + "/data").then((res) => res.json()), + fetch(server + "/fields").then((res) => res.json()) +]).then(([data, fields]) => { + table.setConfig({ data, fields }); + + // 将 serverDataService 集成到 widget 的 Event Bus 执行顺序中 + table.api.setNext(someServerService); +}); +~~~ + +**相关文章**:[`setConfig`](api/methods/setconfig-method.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md new file mode 100644 index 0000000..eaff736 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md @@ -0,0 +1,75 @@ +--- +sidebar_label: getTable() +title: getTable 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 getTable 方法。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载免费的 30 天评估版 DHTMLX Pivot。 +--- + +# getTable() + +### 描述 {#description} + +@short: 获取对 Pivot 表格中底层 Table widget 实例的访问权限 + +此方法用于访问 Pivot 中底层的 Table widget 实例。它提供对 Table 功能的直接访问,支持数据序列化和以各种格式导出等操作。Table API 拥有自己的 `api.exec()` 方法,可以调用 [`open-row`](api/table/open-row.md)、[`close-row`](api/table/close-row.md)、[`export`](api/table/export.md) 和 [`filter-rows`](api/table/filter-rows.md) 事件。 + +### 用法 {#usage} + +~~~jsx +getTable(wait:boolean): Table | Promise; +~~~ + +### 参数 {#parameters} + +`wait` - 定义是否等待 Table API 在 Pivot 中就绪(当 Table API 在 Pivot 初始化期间使用时为必需)。如果值设置为 **true**,该方法将返回一个包含 Table API 的 promise。 + +### 示例 {#example} + +在下面的示例中,我们通过 [`api.exec()`](api/internal/exec-method.md) 方法获取 Table widget API 的访问权限,并在点击按钮时触发 Table 的 `export` 事件。 + +~~~jsx +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 访问 table 实例 +let table_instance = table.getTable(); + +function toCSV() { + table_instance.exec("export", { + options: { + format: "csv", + cols: ";" + } + }); +} + +const exportButton = document.createElement("button"); + +exportButton.addEventListener("click", toCSV); +exportButton.textContent = "Export"; + +document.body.appendChild(exportButton); +~~~ + +**相关文章**: + +- [`close-row`](api/table/close-row.md) +- [`export`](api/table/export.md) +- [`filter-rows`](api/table/filter-rows.md) +- [`open-row`](api/table/open-row.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md new file mode 100644 index 0000000..d5bb3b0 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md @@ -0,0 +1,73 @@ +--- +sidebar_label: setConfig() +title: setConfig() +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 setConfig() 方法。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# setConfig() + +### 描述 {#description} + +@short: 更新 Pivot widget 的当前配置 + +该方法用于更新 Pivot widget 的当前配置。当需要更新 widget 的底层数据集时,此方法非常有用。该方法会保留所有之前设置的、未在 `setConfig` 调用中显式传入的选项。 + +### 用法 {#usage} + +~~~jsx +setConfig(config: { [key:any]: any }): void; +~~~ + +### 参数 {#parameters} + +- `config` - (必填)Pivot 配置对象。完整属性列表请参见[此处](api/overview/properties-overview.md) + +:::important +该方法仅更改您传入的参数。它会销毁当前组件并初始化一个新组件。 +::: + +### 示例 {#example} + +~~~jsx {21-41} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 更新配置参数 +table.setConfig({ + config: { + rows: ["studio", "genre", "duration"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + { + field: "type", + method: "count" + } + ] + } +}); +~~~ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md new file mode 100644 index 0000000..e84e830 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md @@ -0,0 +1,56 @@ +--- +sidebar_label: setLocale() +title: setLocale() +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 setLocale() 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# setLocale() + +### 描述 {#description} + +@short: 为 Pivot 应用新的语言环境 + +### 用法 {#usage} + +~~~jsx +setLocale(null | locale?: object): void; +~~~ + +### 参数 {#parameters} + +- `null` - (可选)重置为默认语言环境(英语) +- `locale` - (可选)要应用的新语言环境的数据对象 + +### 示例 {#example} + +~~~jsx +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// 为 Pivot 应用 "de" 语言环境 +table.setLocale(pivot.locales.de); + +// 为 Pivot 应用默认语言环境 +table.setLocale(); // 或 setLocale(null); +~~~ + +**相关文章**: +- [本地化](guides/localization.md) +- [`locale`](api/config/locale-property.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md new file mode 100644 index 0000000..0b9d7fb --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md @@ -0,0 +1,55 @@ +--- +sidebar_label: showConfigPanel() +title: showConfigPanel() +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 showConfigPanel() 方法。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 30 天免费评估版本。 +--- + +# showConfigPanel() + +### 描述 {#description} + +@short: 显示或隐藏配置面板 + +当需要在不依赖用户交互的情况下控制配置面板的可见性时,此方法非常有用。例如,您可以根据应用程序中的其他交互或状态来隐藏或显示该面板。 + +### 用法 {#usage} + +~~~jsx +showConfigPanel({mode: boolean}): void; +~~~ + +### 参数 {#parameters} + +- `mode`(boolean)—(必填)若值设置为 **true**(默认值),则显示配置面板;若值设置为 **false**,则隐藏配置面板 + +### 示例 {#example} + +~~~jsx {21-23} +// 创建 Pivot +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.showConfigPanel ({ + mode: false +}) +~~~ + +**相关文章**: +- [`show-config-panel` 事件](api/events/show-config-panel-event.md) +- [`configPanel` 属性](api/config/configpanel-property.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/events-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/events-overview.md new file mode 100644 index 0000000..8c36287 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/events-overview.md @@ -0,0 +1,19 @@ +--- +sidebar_label: 事件概览 +title: 事件概览 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查看 JavaScript Pivot 的事件概览。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 30 天免费评估版本。 +--- + +# 事件概览 + +| 名称 | 描述 | +| ------------------------------------------------- | ----------------------------------------------- | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md new file mode 100644 index 0000000..945dad5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md @@ -0,0 +1,15 @@ +--- +sidebar_label: Event Bus 方法 +title: Event Bus 方法 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查看 JavaScript Pivot 内部 Event Bus 方法概览。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# Event Bus 方法概览 {#event-bus-methods-overview} + +| 名称 | 描述 | +| ---------------------------------------------- | ------------------------------------------------- | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md new file mode 100644 index 0000000..bded89f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md @@ -0,0 +1,13 @@ +--- +sidebar_label: State methods +title: State Methods +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查看 JavaScript Pivot 内部 State 方法概述。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# State methods 概述 {#state-methods-overview} + +| 名称 | 描述 | +| ---------------------------------------------- | -------------------------------------------------- | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/main-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/main-overview.md new file mode 100644 index 0000000..1f9897e --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/main-overview.md @@ -0,0 +1,80 @@ +--- +sidebar_label: API 概览 +title: API 概览 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查阅 JavaScript Pivot 的 API 概览。浏览开发者指南和 API 参考,体验代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# API 概览 {#api-overview} + +## Pivot 构造函数 {#pivot-constructor} + +~~~jsx +new pivot.Pivot("#root", { + // 配置参数 +}); +~~~ + +**参数**: + +- HTML 容器(HTML 容器的 ID) +- 配置参数对象([请参阅此处](#pivot-properties)) + +## Pivot 方法 {#pivot-methods} + +| 名称 | 描述 | +| ------------------------------------------- | ---------------------------------- | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | + +## Pivot 内部 API {#pivot-internal-api} + +### Event Bus 方法 {#event-bus-methods} + +| 名称 | 描述 | +| :------------------------------------ | :------------------------------------------- | +| [](api/internal/detach-method.md) | @getshort(../internal/detach-method.md) | +| [](api/internal/exec-method.md) | @getshort(../internal/exec-method.md) | +| [](api/internal/intercept-method.md) | @getshort(../internal/intercept-method.md) | +| [](api/internal/on-method.md) | @getshort(../internal/on-method.md) | +| [](api/internal/setnext-method.md) | @getshort(../internal/setnext-method.md) | + +### 状态方法 {#state-methods} + +| 名称 | 描述 | +| :---------------------------------------------- | :------------------------------------------------- | +| [](api/internal/getreactivestate-method.md) | @getshort(../internal/getreactivestate-method.md) | +| [](api/internal/getstate-method.md) | @getshort(../internal/getstate-method.md) | +| [](api/internal/getstores-method.md) | @getshort(../internal/getstores-method.md) | + +## Pivot 事件 {#pivot-events} + +| 名称 | 描述 | +| :------------------------------------------------ | :---------------------------------------------- | +| [](api/events/add-field-event.md) | @getshort(../events/add-field-event.md) | +| [](api/events/apply-filter-event.md) | @getshort(../events/apply-filter-event.md) | +| [](api/events/delete-field-event.md) | @getshort(../events/delete-field-event.md) | +| [](api/events/move-field-event.md) | @getshort(../events/move-field-event.md) | +| [](api/events/open-filter-event.md) | @getshort(../events/open-filter-event.md) | +| [](api/events/render-table-event.md) | @getshort(../events/render-table-event.md) | +| [](api/events/show-config-panel-event.md) | @getshort(../events/show-config-panel-event.md) | +| [](api/events/update-config-event.md) | @getshort(../events/update-config-event.md) | +| [](api/events/update-field-event.md) | @getshort(../events/update-field-event.md) | + +## Pivot 属性 {#pivot-properties} + +| 名称 | 描述 | +| :------------------------------------------------- | :----------------------------------------------- | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md new file mode 100644 index 0000000..2dbd4b5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md @@ -0,0 +1,14 @@ +--- +sidebar_label: 方法概览 +title: 方法概览 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查看 JavaScript Pivot 的方法概览。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# 方法概览 {#methods-overview} + +| 名称 | 描述 | +| ------------------------------------------- | ----------------------------------------------- | +| [](api/methods/gettable-method.md) | @getshort(../methods/gettable-method.md) | +| [](api/methods/setconfig-method.md) | @getshort(../methods/setconfig-method.md) | +| [](api/methods/setlocale-method.md) | @getshort(../methods/setlocale-method.md) | +| [](api/methods/showconfigpanel-method.md) | @getshort(../methods/showconfigpanel-method.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md new file mode 100644 index 0000000..b22e9d4 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md @@ -0,0 +1,24 @@ +--- +sidebar_label: 属性概览 +title: 属性概览 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查看 JavaScript Pivot 的属性概览。浏览开发指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# 属性概览 + +如需配置 **Pivot**,请参阅[配置](guides/configuration.md)章节。 + +| 名称 | 描述 | +| -------------------------------------------------- | ------------------------------------------------ | +| [](api/config/columnshape-property.md) | @getshort(../config/columnshape-property.md) | +| [](api/config/config-property.md) | @getshort(../config/config-property.md) | +| [](api/config/configpanel-property.md) | @getshort(../config/configpanel-property.md) | +| [](api/config/data-property.md) | @getshort(../config/data-property.md) | +| [](api/config/fields-property.md) | @getshort(../config/fields-property.md) | +| [](api/config/headershape-property.md) | @getshort(../config/headershape-property.md) | +| [](api/config/limits-property.md) | @getshort(../config/limits-property.md) | +| [](api/config/locale-property.md) | @getshort(../config/locale-property.md) | +| [](api/config/methods-property.md) | @getshort(../config/methods-property.md) | +| [](api/config/predicates-property.md) | @getshort(../config/predicates-property.md) | +| [](api/config/readonly-property.md) | @getshort(../config/readonly-property.md) | +| [](api/config/tableshape-property.md) | @getshort(../config/tableshape-property.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md new file mode 100644 index 0000000..c49b86f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md @@ -0,0 +1,16 @@ +--- +sidebar_label: Table 事件概览 +title: Table 事件概览 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中查阅 JavaScript Pivot 的 Table 事件概览。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +# Table 事件概览 {#table-events-overview} + +Pivot API 的 [`getTable`](api/methods/gettable-method.md) 方法允许访问 Pivot 内部底层 Table widget 实例,并执行以下 Table 事件: + +| 名称 | 描述 | +| ------------------------------------------------- | ----------------------------------------------- | +| [](api/table/close-row.md) | @getshort(../table/close-row.md) | +| [](api/table/export.md) | @getshort(../table/export.md) | +| [](api/table/filter-rows.md) | @getshort(../table/filter-rows.md) | +| [](api/table/open-row.md) | @getshort(../table/open-row.md) | diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/table/close-row.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/close-row.md new file mode 100644 index 0000000..c8c1dbf --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/close-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: close-row +title: close-row +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 close-row 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本 +--- + +# close-row + +### 描述 {#description} + +@short: 在折叠行时触发 + +若要触发 Table 事件,需要通过 [`getTable`](api/methods/gettable-method.md) 方法获取 Pivot 内部的 Table 组件实例。树形模式需通过 [`tableShape`](api/config/tableshape-property.md) 属性启用。 + +### 用法 {#usage} + +```jsx {} +"close-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### 参数 {#parameters} + +该操作的回调函数接收一个包含以下参数的对象: + +- `id` - (必填)具有嵌套行的行 id +- `nested` - (可选)若设置为 **true**,所有嵌套项将被折叠 + +:::note +若 `id` 设为 0 且 `nested` 设为 **true**,表格中的所有行都将被折叠 +::: + +### 示例 {#example} + +以下代码片段演示了如何通过按钮点击展开/折叠所有行: + + + +**相关文章**: +- [`getTable`](api/methods/gettable-method.md) +- [展开/折叠所有行](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/table/export.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/export.md new file mode 100644 index 0000000..cb7fee5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/export.md @@ -0,0 +1,109 @@ +--- +sidebar_label: export +title: export +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 export 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本 +--- + +# export + +### 描述 {#description} + +@short: 在导出数据时触发 + +要触发 Table 事件,需要通过 [`getTable`](api/methods/gettable-method.md) 方法访问 Pivot 内部的 Table 实例。 + +### 用法 {#usage} + +```jsx +"export": ({ + options: { + format: "csv" | "xlsx", + fileName?: string, + header?: boolean, + footer?: boolean, + download?: boolean, + + /* XLSX 设置*/ + styles?: boolean | { + header?: { + fontWeight?: "bold", + color?: string, + background?: string, + align?: "left"|"right"|"center", + borderBottom?: string, + borderRight?: string, + } + lastHeaderCell?: { /* 与 header 相同 */ }, + cell?: { /* 与 header 相同 */ }; + firstFooterCell?: { /* 与 header 相同 */ }, + footer?: {/* 与 header 相同 */}, + } + cellTemplate?: (value: any, row: any, column: object ) + => string | null, + headerCellTemplate?: (text: string, cell: object, column: object, type: "header"| "footer") + => string | null, + cellStyle?: (value: any, row: any, column: object) + => { format: string; align: "left"|"right"|"center" } | null, + headerCellStyle?: (text: string, cell: object, column: object, type: "header"| "footer") + => { format: string; align: "left"|"right"|"center" } | null, + sheetName?: string, + + /* CSV 设置 */ + rows: string, + cols: string, + }, + result?: any, +}) => boolean|void; +``` + +Table widget 的 `export` 动作具有以下可配置参数: + +- `options` - 包含导出选项的对象;选项因格式类型而异 +- `result` - 导出的 Excel 或 CSV 数据的结果(通常为 Blob 或文件,取决于 `download` 选项) + + **两种格式("csv" 和 "xlsx")的通用选项**: + + - `format` (string) - (可选)导出格式,可以是 "csv" 或 "xlsx" + - `fileName` (string) - (可选)文件名(默认为 "data") + - `header` (boolean) - (可选)定义是否导出表头(默认为 **true**) + - `footer` (boolean) - (可选)定义是否导出表尾(默认为 **true**) + - `download` (boolean) - (可选)定义是否下载文件。默认设置为 **true**。若设置为 **false**,文件将不会被下载,Excel 或 CSV 数据(Blob)将通过 `ev.result` 获取 + + **"xlsx" 格式专有选项**: + + - `sheetName` (string) - Excel 工作表的名称(默认为 "data") + - `styles` (boolean 或对象) - 若设置为 **false**,表格将不带任何样式导出;可通过样式属性的哈希对象进行配置: + - `header` - 包含表头单元格设置的对象: + - `fontWeight` (string) - (可选)可设置为 "bold";若未设置,字体将为普通样式 + - `color` (string) - (可选)表头的文字颜色 + - `background` (string) - (可选)表头的背景颜色 + - `align` - (可选)文字对齐方式,可为 "left"|"right"|"center"。若未设置,将应用 Excel 中设置的对齐方式 + - `borderBottom` (string) - (可选)底部边框的样式 + - `borderRight` (string) - (可选)右侧边框的样式(例如,*borderRight: "0.5px solid #dfdfdf"*) + - `lastHeaderCell` - 表头最后一行单元格的样式属性,与 *header* 的属性相同 + - `cell` - 表体单元格的样式属性,与 *header* 的属性相同 + - `firstFooterCell` - 表尾第一行单元格的样式属性,与 *header* 的属性相同 + - `footer` - 表尾单元格的样式属性,与 *header* 的属性相同 + - `cellTemplate` - 用于自定义每个单元格导出值的函数。接受 value、row 和 column 对象作为参数,返回要导出的自定义值 + - `headerCellTemplate` - 在导出时自定义表头或表尾单元格值的函数。调用时传入文本、表头单元格对象、列对象以及单元格类型("header" 或 "footer"),允许用户修改导出的表头/表尾值 + - `cellStyle` - 在导出时自定义各单元格样式和格式的函数。接受 value、row 和 column 对象作为参数,应返回包含样式属性(如对齐方式或格式)的对象 + - `headerCellStyle` - 与 cellStyle 类似,但专用于表头和表尾单元格。该函数接受文本、表头单元格对象、列对象以及类型("header" 或 "footer"),并返回样式属性 + :::note + 默认情况下,对于 "xlsx" 格式,日期和数字字段将以原始值导出,使用默认格式或通过 [`fields`](api/config/fields-property.md) 属性定义的格式。但如果为某个字段定义了模板(参见 [`tableShape`](api/config/tableshape-property.md) 属性),则会导出该模板定义的渲染值。若同时设置了模板和 `format`,模板设置将覆盖格式设置。 + ::: + + **"csv" 格式专有选项**: + + - `rows` (string) - (可选)行分隔符,默认为 "\n" + - `cols` (string) - (可选)列分隔符,默认为 "\t" + +## 示例 {#example} + +以下代码片段展示了如何导出数据: + + + +**相关文章**: +- [`getTable`](api/methods/gettable-method.md) +- [导出数据](guides/exporting-data.md) +- [为字段应用格式](guides/working-with-data.md#applying-formats-to-fields) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/table/filter-rows.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/filter-rows.md new file mode 100644 index 0000000..e8c435b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/filter-rows.md @@ -0,0 +1,35 @@ +--- +sidebar_label: filter-rows +title: filter-rows +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 filter-rows 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本 +--- + +# filter-rows + +### 描述 {#description} + +@short: 在过滤数据时触发 + +要触发 Table 事件,需要通过 [`getTable`](api/methods/gettable-method.md) 方法获取 Pivot 内部 Table 实例的访问权限。 + +### 用法 {#usage} + +```jsx {} +"filter-rows": ({ + filter?: any +}) => boolean|void; +``` + +### 参数 {#parameters} + +该动作的回调函数接收一个包含以下参数的对象: + +- `filter` - (可选)任意过滤函数,对数据数组中的每个条目进行处理,并为每个条目返回 **true** 或 **false** + +### 示例 {#example} + +以下代码片段演示了如何根据输入值过滤表格正文中已聚合(可见)的数据: + + + +**相关文章**:[`getTable`](api/methods/gettable-method.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/api/table/open-row.md b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/open-row.md new file mode 100644 index 0000000..4dc0653 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/api/table/open-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: open-row +title: open-row +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解 open-row 事件。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本 +--- + +# open-row + +### 描述 {#description} + +@short: 在展开行时触发 + +要触发 Table 事件,需要通过 [`getTable`](api/methods/gettable-method.md) 方法访问 Pivot 内部的 Table 实例。树形模式应通过 [`tableShape`](api/config/tableshape-property.md) 属性启用。 + +### 用法 {#usage} + +```jsx {} +"open-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### 参数 {#parameters} + +该操作的回调接收一个包含以下参数的对象: + +- `id` - (必填)具有嵌套行的行的 id +- `nested` - (可选)若设置为 **true**,所有嵌套项将被展开 + +:::note +若 `id` 设置为 0 且 `nested` 设置为 **true**,表格中所有行都将被展开 +::: + +### 示例 {#example} + +以下代码片段演示了如何通过按钮点击展开/折叠所有行: + + + +**相关文章**: +- [`getTable`](api/methods/gettable-method.md) +- [展开/折叠所有行](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/add_remove.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/add_remove.png new file mode 100644 index 0000000..81dcb52 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/add_remove.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/apply_filter.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/apply_filter.png new file mode 100644 index 0000000..53905a7 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/apply_filter.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/config_panel.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/config_panel.png new file mode 100644 index 0000000..41b7568 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/config_panel.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/filter.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/filter.png new file mode 100644 index 0000000..b4b1599 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/filter.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/filter_applied.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/filter_applied.png new file mode 100644 index 0000000..9ed7479 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/filter_applied.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/operations.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/operations.png new file mode 100644 index 0000000..80f6f79 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/operations.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/pivot-main.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/pivot-main.png new file mode 100644 index 0000000..5eaa953 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/pivot-main.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/priority.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/priority.png new file mode 100644 index 0000000..a827e01 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/priority.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/table.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/table.png new file mode 100644 index 0000000..f0fb3a9 Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/table.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/assets/trial_pivot.png b/i18n/zh/docusaurus-plugin-content-docs/current/assets/trial_pivot.png new file mode 100644 index 0000000..f2e21cf Binary files /dev/null and b/i18n/zh/docusaurus-plugin-content-docs/current/assets/trial_pivot.png differ diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/configuration.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/configuration.md new file mode 100644 index 0000000..40013c3 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/configuration.md @@ -0,0 +1,740 @@ +--- +sidebar_label: 配置 +title: 配置 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解配置相关内容。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天试用版本。 +--- + +# 配置 {#configuration} + +通过以下 API 配置 Pivot 表格和配置面板: + +- [`config`](api/config/config-property.md) — 定义 Pivot 表格的结构及数据聚合方式 +- [`render-table`](api/events/render-table-event.md) — 动态更改表格配置 +- [`tableShape`](api/config/tableshape-property.md) — 配置 Pivot 表格的外观 +- [`columnShape`](api/config/columnshape-property.md) — 配置列的外观和行为 +- [`headerShape`](api/config/headershape-property.md) — 配置表头的外观和行为 +- [`configPanel`](api/config/configpanel-property.md) — 控制配置面板的显示状态 +- [`setLocale`](api/methods/setlocale-method.md) — 应用语言环境(参见[本地化](guides/localization.md)) +- [`data`](api/config/data-property.md)、[`fields`](api/config/fields-property.md) — 加载数据和字段元数据 +- [`predicates`](api/config/predicates-property.md) — 在聚合前对数据进行预处理 +- [`methods`](api/config/methods-property.md) — 定义自定义聚合方法 +- [`limits`](api/config/limits-property.md) — 限制最终数据集中的行数和列数 + +有关数据操作的说明,请参见[数据操作](guides/working-with-data.md)。 + +您可以配置以下 Pivot 表格元素: + +- 列和行 +- 表头和表脚 +- 单元格 +- 表格尺寸 + +## 调整表格尺寸 {#resizing-the-table} + +使用 [`tableShape`](api/config/tableshape-property.md) 属性更改行、列、表头和表脚的尺寸。 + +以下代码片段展示了默认尺寸: + +~~~jsx +const sizes = { + rowHeight: 34, + headerHeight: 30, + footerHeight: 30, + columnWidth: 150 +}; +~~~ + +以下代码片段覆盖了默认尺寸: + +~~~jsx {4-11} +const table = new pivot.Pivot("#root", { + fields, + data, + tableShape: { + sizes: { + rowHeight: 44, + headerHeight: 60, + footerHeight: 30, + columnWidth: 170 + } + }, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +:::info +要设置特定列的宽度,请使用 [`columnShape`](api/config/columnshape-property.md) 属性的 `width` 参数。 +::: + +## 自动调整列宽以适应内容 {#autosize-columns-to-content} + +使用 [`columnShape`](api/config/columnshape-property.md) 属性的 `autoWidth` 参数自动计算列宽。所有 `autoWidth` 子参数均为可选项——完整说明请参见 [`columnShape`](api/config/columnshape-property.md) 参考文档。 + +`autoWidth` 对象接受以下参数: + +- `columns` — 选择哪些字段启用自动计算宽度的对象 +- `auto` — 根据表头、单元格内容或两者来调整宽度 +- `maxRows` — 用于检测列尺寸所分析的数据行数(默认值:20) +- `firstOnly` — 若为 `true`(默认值),则每个字段仅分析一次。当多列基于同一字段时(例如,`oil` 对应 `count` 和 `oil` 对应 `sum`),仅分析第一列,其余列继承其宽度 + +以下代码片段为四个字段启用 `autoWidth` 并禁用 `firstOnly`,使每列独立进行宽度计算: + +~~~jsx {18-30} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + autoWidth: { + // 为这些字段计算列宽 + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + // 分析所有字段 + firstOnly: false + } + } +}); +~~~ + +## 为单元格应用模板 {#applying-templates-to-cells} + +### 通过 tableShape 添加模板 {#add-templates-via-tableshape} + +使用 [`tableShape`](api/config/tableshape-property.md) 属性的 `templates` 参数通过函数渲染单元格值。每个键为字段 ID,每个值为返回字符串的函数。基于指定字段的所有列均会应用该模板。 + +以下示例为 `state` 单元格应用模板,显示州的组合名称(全名加缩写): + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", + // 其他值 +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // 自定义 "state" 单元格的值 + state: v => v + ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // 其他值 + ], + }, + fields, +}); +~~~ + +### 通过 template 辅助函数添加模板 {#adding-a-template-via-the-template-helper} + +要在正文单元格中插入 HTML 内容,请使用 [`pivot.template`](api/helpers/template.md) 辅助函数,并将结果赋值给列对象的 `cell` 属性。通过 [`api.intercept`](api/internal/intercept-method.md) 方法拦截 [`render-table`](api/events/render-table-event.md) 事件,在表格渲染前应用模板。 + +以下示例根据字段(`id`、`user_score`)为正文单元格添加图标(星形或旗帜形): + +~~~js +function cellTemplate(value, method, row, column) { + const field = column.fields ? column.fields[row.$level] : column.field; + + if (field === "id") { + return idTemplate(value); + } + + if (field === "user_score") { + return scoreTemplate(value); + } + + return value; +} + +function idTemplate(value) { + const name = value?.toString().split("-")[0]; + return ` ${value}`; +} + +function scoreTemplate(value) { + return ` ${value}`; +} + +widget.api.intercept("render-table", ({ config: tableConfig }) => { + tableConfig.columns = tableConfig.columns.map((c) => { + if (c.area === "rows") { + // 为 "rows" 区域的列单元格应用模板 + c.cell = pivot.template(({ value, method, row, column }) => cellTemplate(value, method, row, column)); + } + return c; + }); +}); +~~~ + +## 为表头应用模板 {#applying-templates-to-headers} + +### 通过 headerShape 添加模板 {#add-templates-via-headershape} + +要控制表头中的文本格式,请使用 [`headerShape`](api/config/headershape-property.md) 属性的 `template` 参数。该参数为一个函数,其: + +- 接收字段标签、ID 和子标签(方法名,如有) +- 返回处理后的值 + +默认模板为: + +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +在没有自定义模板的情况下,`values` 区域的字段显示标签和方法(例如 `Oil(count)`),其他区域的字段显示 `label` 值。[`predicates`](api/config/predicates-property.md) 模板会覆盖 `headerShape` 模板。 + +以下示例将表头文本转换为小写,生成如 `profit (sum)` 的标签: + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // 表头文本的自定义模板 + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // 其他值 + ], + }, + fields, +}); +~~~ + +### 通过 template 辅助函数添加模板 {#add-templates-via-the-template-helper} + +要在表头单元格中插入 HTML 内容,请使用 [`pivot.template`](api/helpers/template.md) 辅助函数,并将结果赋值给表头单元格对象的 `cell` 属性。通过 [`api.intercept`](api/internal/intercept-method.md) 方法拦截 [`render-table`](api/events/render-table-event.md) 事件,在表格渲染前应用模板。 + +以下示例为以下位置添加图标: + +- 基于字段名称的表头标签(例如,`id` 字段显示地球图标) +- 基于单元格值的列表头(根据 `status` 值显示带颜色的箭头指示符) + +~~~jsx +function rowsHeaderTemplate(value, field) { + let icon = ""; + if (field === "id") icon = ""; + if (field === "user_score") icon = ""; + return `${value} ${icon}`; +} + +function statusTemplate(value) { + let icon = ""; + if (value === "Up") icon = ""; + if (value === "Down") icon = ""; + return `${value} ${icon}`; +} + +widget.api.intercept("render-table", ({ config: tableConfig }) => { + tableConfig.columns = tableConfig.columns.map((c) => { + if (c.area === "rows") { + // 为 "rows" 区域列的第一行表头应用模板 + c.header[0].cell = pivot.template(({ value, field }) => rowsHeaderTemplate(value, field)); + } else { + // 显示 "status" 字段值的表头单元格 + const headerCell = c.header.find((h) => h.field === "status"); + if (headerCell) { + headerCell.cell = pivot.template(({ value }) => statusTemplate(value)); + } + } + return c; + }); +}); +~~~ + +## 使列可折叠 {#make-columns-collapsible} + +要允许用户折叠和展开共享表头下的列,请将 [`headerShape`](api/config/headershape-property.md) 属性的 `collapsible` 参数设置为 `true`。 + +以下代码片段启用可折叠表头列: + +~~~jsx {4-6} +const table = new pivot.Pivot("#root", { + fields, + data, + headerShape: { + collapsible: true, + }, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## 冻结列 {#freezing-columns} + +将列冻结在左侧或右侧,使其在表格其余部分滚动时保持可见。使用 [`tableShape`](api/config/tableshape-property.md) 属性的 `split` 参数,并将 `left` 或 `right` 设置为 `true`。 + +### 在左侧冻结列 {#freeze-columns-on-the-left} + +当 `split.left` 为 `true` 时,冻结列数等于 [`config`](api/config/config-property.md) 属性中 `rows` 字段的数量。在树形模式下,无论 `rows` 字段数量多少,仅冻结一列。 + +以下代码片段在左侧冻结一列(定义了一个 `rows` 字段): + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + split: {left: true } + } +}); +~~~ + +要设置自定义分割数量,请监听 [`render-table`](api/events/render-table-event.md) 事件并覆盖 `tableConfig.split`。请避免分割包含合并列的列。 + +以下代码片段在左侧冻结所有 `rows` 列以及两倍 `values` 字段数量的列: + +~~~jsx {19-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + { + field: "oil", + method: "sum" + }, + { + field: "oil", + method: "count" + } + ] + } +}); +table.api.on("render-table", ({ config: tableConfig }) => { + const { config } = table.api.getState(); + + tableConfig.split = { + left: config.rows.length + config.values.length * 2 + }; +}); +~~~ + +### 在右侧冻结列 {#freezing-columns-on-the-right} + +将 `split.right` 设置为 `true` 以在右侧冻结合计列。 + +以下代码片段在右侧冻结合计列: + +~~~jsx {4-7} +const widget = new pivot.Pivot("#pivot", { + fields, + data: dataset, + tableShape:{ + split: {right: true}, + totalColumn: true, + }, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +要在右侧冻结自定义数量的列,请监听 [`render-table`](api/events/render-table-event.md) 事件并覆盖 `tableConfig.split`。请避免分割包含合并列的列。 + +以下代码片段在右侧冻结与 `values` 字段数量相同的列: + +~~~jsx {20-25} +const widget = new pivot.Pivot("#pivot", { + fields, + data: dataset, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); + +widget.api.on("render-table", ({ config: tableConfig }) => { + const { config } = widget.api.getState(); + tableConfig.split = { + right: config.values.length, + } +}) +~~~ + +## 列排序 {#sort-in-columns} + +UI 中的排序功能默认启用——用户单击列表头即可排序。要禁用排序,请将 [`columnShape`](api/config/columnshape-property.md) 属性的 `sort` 参数设置为 `false`。 + +以下代码片段禁用 UI 排序: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +有关默认排序、自定义比较器和运行时更新的更多信息,请参见[数据排序](guides/working-with-data.md#sorting-data)。 + +## 启用树形模式 {#enabling-the-tree-mode} + +树形模式以层级结构展示数据,行可展开折叠。将 [`tableShape`](api/config/tableshape-property.md) 属性的 `tree` 参数设置为 `true`(默认值为 `false`)。[`config`](api/config/config-property.md) 中 `rows` 数组的第一个字段成为父行。 + +以下代码片段以 `studio` 为父级、`genre` 为嵌套行启用树形模式: + +~~~jsx {3} +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true + }, + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "max" + } + ] + } +}); +~~~ + +## 展开或折叠所有行 {#expandingcollapsing-all-rows} + +要以编程方式展开或折叠所有行,请通过 [`tableShape`](api/config/tableshape-property.md) 属性启用树形模式。然后使用 [`getTable`](api/methods/gettable-method.md) 方法获取 Table 组件实例,并通过 Table 的 `api.exec` 方法触发 [`open-row`](api/table/open-row.md) 或 [`close-row`](api/table/close-row.md) 事件。 + +以下示例渲染"展开全部"和"折叠全部"按钮,在树形模式下展开或折叠所有分支: + +~~~jsx +const table = new pivot.Pivot("#root", { + tableShape: { + tree: true + }, + fields, + data: dataset, + config: { + rows: ["type", "studio"], + columns: [], + values: [ + { + field: "score", + method: "max" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + }, + { + field: "episodes", + method: "count" + } + ] + } +}); + +const api = table.api; +const tableInstance = api.getTable(); +// 渲染时保持所有表格分支关闭 +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // 在此返回 false 以阻止表格渲染 + // return false; +}); + +function openAll() { + tableInstance.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableInstance.exec("close-row", { id: 0, nested: true }); +} + +const openAllButton = document.createElement("button"); +openAllButton.addEventListener("click", openAll); +openAllButton.textContent = "Open all"; + +const closeAllButton = document.createElement("button"); +closeAllButton.addEventListener("click", closeAll); +closeAllButton.textContent = "Close all"; + +document.body.appendChild(openAllButton); +document.body.appendChild(closeAllButton); +~~~ + +## 更改表头文本方向 {#change-header-text-orientation} + +要将表头文本从水平方向旋转为垂直方向,请将 [`headerShape`](api/config/headershape-property.md) 属性的 `vertical` 参数设置为 `true`。 + +以下代码片段渲染垂直表头文本: + +~~~jsx {4-6} +const table = new pivot.Pivot("#root", { + fields, + data, + headerShape: { + vertical: true + }, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## 控制配置面板的显示状态 {#controlling-visibility-of-configuration-panel} + +配置面板默认显示。用户可通过**隐藏设置** / **显示设置**按钮切换显示状态。通过 [`configPanel`](api/config/configpanel-property.md) 属性、[`show-config-panel`](api/events/show-config-panel-event.md) 事件或 [`showConfigPanel`](api/methods/showconfigpanel-method.md) 方法以编程方式控制面板。 + +### 隐藏配置面板 {#hide-the-configuration-panel} + +要在初始化时隐藏面板,请将 [`configPanel`](api/config/configpanel-property.md) 属性设置为 `false`。 + +以下代码片段初始化时隐藏面板的 Pivot: + +~~~jsx +// 初始化时隐藏配置面板 +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + configPanel: false, + config: { + rows: ["hobbies"], + columns: ["relationship_status"], + values: [ + { + field: "age", + method: "min" + }, + { + field: "age", + method: "max" + } + ] + } +}); +~~~ + +要在运行时切换面板,请使用 [`api.exec`](api/internal/exec-method.md) 方法触发 [`show-config-panel`](api/events/show-config-panel-event.md) 事件,并将 `mode` 参数设置为 `false`。 + +以下代码片段在初始化后隐藏面板: + +~~~jsx {19-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +// 隐藏配置面板 +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +### 禁用默认切换功能 {#disable-the-default-toggling} + +要完全阻止默认切换按钮,请使用 [`api.intercept`](api/internal/intercept-method.md) 方法拦截 [`show-config-panel`](api/events/show-config-panel-event.md) 事件并返回 `false`。 + +以下代码片段禁用切换按钮: + +~~~jsx {20-22} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +table.api.intercept("show-config-panel", () => { + return false; +}); +~~~ + +如需使用其他 API,请使用 [`showConfigPanel`](api/methods/showconfigpanel-method.md) 方法。 + +### 面板中的字段操作 {#actions-with-fields-in-the-panel} + +配置面板支持以下字段操作: + +- [`add-field`](api/events/add-field-event.md) — 将字段添加到区域 +- [`delete-field`](api/events/delete-field-event.md) — 从区域移除字段 +- [`update-field`](api/events/update-field-event.md) — 更新字段的方法或设置 +- [`move-field`](api/events/move-field-event.md) — 在区域内对字段重新排序 + +**相关示例**: +- [Pivot 2. 为表格和表头单元格添加文本模板](https://snippet.dhtmlx.com/n9ylp6b2) +- [Pivot 2. 自定义冻结(固定)列(自定义数量)](https://snippet.dhtmlx.com/53erlmgp) +- [Pivot 2. 展开和折叠所有行](https://snippet.dhtmlx.com/i4mi6ejn) +- [Pivot 2. 左侧和右侧的冻结(固定)列](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. 排序](https://snippet.dhtmlx.com/j7vtief6) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/exporting-data.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/exporting-data.md new file mode 100644 index 0000000..f4801ed --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/exporting-data.md @@ -0,0 +1,45 @@ +--- +sidebar_label: 导出数据 +title: 导出数据 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解如何导出数据。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 导出数据 + +Pivot 通过底层 Table widget 将表格数据导出为 XLSX 或 CSV 格式。使用 [`getTable`](api/methods/gettable-method.md) 方法获取 Table 实例,然后通过 Table 的 [`api.exec`](api/internal/exec-method.md) 方法触发 [`export`](api/table/export.md) 事件。 + +以下示例获取 Table 实例并以 CSV 和 XLSX 格式触发 `export` 事件: + +~~~jsx +const widget = new pivot.Pivot("#root", { /* settings */ }); + +widget.getTable().exec("export", { + options: { + format: "csv", + cols: ";" + } +}); + +widget.getTable().exec("export", { + options: { + format: "xlsx", + fileName: "My Report", + sheetName: "Quarter 1" + } +}); +~~~ + +:::tip +[`getTable`](api/methods/gettable-method.md) 方法接受一个可选的布尔参数 `wait`。传入 `true` 可返回一个 Promise,该 Promise 在 Table API 可用后 resolve。适用于在 Pivot 初始化期间需要 Table API 就绪的场景。 +::: + +## 示例 {#example} + +以下代码片段演示了数据导出: + + + +**相关文章**: + +- [日期格式化](guides/localization.md#date-formatting) +- [`export`](api/table/export.md) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/initialization.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/initialization.md new file mode 100644 index 0000000..e79056f --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/initialization.md @@ -0,0 +1,86 @@ +--- +sidebar_label: 初始化 +title: 初始化 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解初始化相关内容。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 初始化 {#initialization} + +本指南介绍如何在页面上创建 Pivot 并为您的应用程序添加 Pivot 表格功能。请按照以下步骤完成组件的初始化: + +1. [在页面中引入 Pivot 源文件](#include-source-files)。 +2. [为 Pivot 创建容器](#create-a-container)。 +3. [使用构造函数初始化 Pivot](#initialize-pivot)。 + +## 引入源文件 {#include-source-files} + +Pivot 应用需要在页面中引入两个源文件。有关下载软件包的说明,请参阅[下载软件包](how-to-start.md#step-1-downloading-and-installing-packages)。 + +请引入以下文件: + +- *pivot.js* +- *pivot.css* + +设置源文件的正确相对路径: + +~~~html title="index.html" + + +~~~ + +## 创建容器 {#create-a-container} + +Pivot 渲染到 HTML 容器元素中。添加一个容器并为其指定 ID,例如 *"root"*: + +~~~html title="index.html" +
+~~~ + +## 初始化 Pivot {#initialize-pivot} + +`pivot.Pivot` 构造函数接受两个参数: + +- HTML 容器的 ID +- 包含配置属性的对象 + +以下代码片段在 *"root"* 容器中创建一个 Pivot 实例,并设置初始字段、数据和结构: + +~~~jsx +// 创建 Pivot +const table = new pivot.Pivot("#root", { + // 配置属性 + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +构造函数返回一个 Pivot 实例。可在返回的实例上调用以下 API 方法: + +- [`getTable`](api/methods/gettable-method.md) — 获取底层 Table 组件实例 +- [`setConfig`](api/methods/setconfig-method.md) — 更新当前 Pivot 配置 +- [`setLocale`](api/methods/setlocale-method.md) — 为 Pivot 应用新的语言环境 +- [`showConfigPanel`](api/methods/showconfigpanel-method.md) — 显示或隐藏配置面板 + +## 配置属性 {#configuration-properties} + +Pivot 构造函数接受一个包含配置属性的对象,用于控制数据、布局和行为。 + +:::info +有关配置 Pivot 的完整属性列表,请参阅[属性概览](api/overview/properties-overview.md)。 +::: + +## 示例 {#example} + +以下代码片段使用初始数据初始化 Pivot: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md new file mode 100644 index 0000000..dfd3525 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md @@ -0,0 +1,325 @@ +--- +sidebar_label: 与 Angular 集成 +title: 与 Angular 集成 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解与 Angular 的集成方法。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载免费 30 天评估版 DHTMLX Pivot。 +--- + +# 与 Angular 集成 {#integration-with-angular} + +:::tip +本文假设您已熟悉 **Angular** 的基本概念和使用模式。如需复习,请参阅 [**Angular 文档**](https://v17.angular.io/docs)。 +::: + +DHTMLX Pivot 可作为普通组件与 **Angular** 集成。完整的可运行示例请参见 [**GitHub 上的 Angular Pivot 演示**](https://github.com/DHTMLX/angular-pivot-demo)。 + +## 创建项目 {#create-a-project} + +:::info +开始之前,请先安装 [**Angular CLI**](https://v1.angular.io/cli) 和 [**Node.js**](https://nodejs.org/en/)。 +::: + +以下命令将创建一个名为 *my-angular-pivot-app* 的新 Angular 项目: + +~~~bash +ng new my-angular-pivot-app +~~~ + +:::note +当 Angular CLI 询问时,请禁用服务器端渲染(SSR)和静态站点生成(SSG/Prerendering)——本指南假设使用客户端渲染应用。 +::: + +该命令会安装所有必要的工具,无需执行其他命令。 + +### 安装依赖 {#install-dependencies} + +切换到新项目目录: + +~~~bash +cd my-angular-pivot-app +~~~ + +使用 [**yarn**](https://yarnpkg.com/) 包管理器安装依赖并启动开发服务器: + +~~~bash +yarn +yarn start # 或者:yarn dev +~~~ + +应用将在本地端口运行(例如 `http://localhost:3000`)。 + +## 创建 Pivot {#create-pivot} + +将 Pivot 包添加到项目中,然后将 Pivot 封装为 Angular 组件。 + +### 第一步:安装包 {#step-1-install-the-package} + +下载 [**试用版 Pivot 包**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) 并按照 README 中的步骤操作。试用版 Pivot 包有效期为 30 天。 + +### 第二步:创建组件 {#step-2-create-the-component} + +创建一个用于挂载 Pivot 的 Angular 组件。在 *src/app/* 下新建 *pivot* 文件夹,并创建 *src/app/pivot/pivot.component.ts*。然后按以下步骤操作: + +#### 导入源文件 {#import-source-files} + +打开 *src/app/pivot/pivot.component.ts* 并导入 Pivot 包。导入路径取决于所使用的版本: + +- **PRO 版本**(从本地文件夹安装): + +~~~jsx +import { Pivot } from 'dhx-pivot-package'; +~~~ + +- **试用版本**: + +~~~jsx +import { Pivot } from '@dhx/trial-pivot'; +~~~ + +本教程使用 Pivot 的试用版本。 + +#### 设置容器并挂载 Pivot {#set-up-the-container-and-mount-pivot} + +要在页面上显示 Pivot,需在组件模板中定义一个容器元素,然后在 `ngOnInit` 钩子中使用构造函数初始化 Pivot,并在 `ngOnDestroy` 钩子中销毁 Pivot。 + +以下代码片段定义了一个最小化的 Pivot Angular 组件: + +~~~jsx {1,8,12-13,18-19} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation } from '@angular/core'; + +@Component({ + encapsulation: ViewEncapsulation.None, + selector: "pivot", // 模板名称,在 "app.component.ts" 文件中以 形式使用 + styleUrls: ["./pivot.component.css"], // 引入 CSS 文件 + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + // Pivot 的容器引用 + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + // 初始化 Pivot 组件 + this._table = new Pivot(this.pivot_container.nativeElement, {}); + } + + ngOnDestroy(): void { + this._table.destructor(); // 卸载时销毁 Pivot + } +} +~~~ + +#### 添加样式 {#add-styles} + +要正确渲染 Pivot,请创建 *src/app/pivot/pivot.component.css*,为页面和 Pivot 容器添加样式: + +~~~css title="pivot.component.css" +/* 导入 Pivot 样式 */ +@import "@dhx/trial-pivot/dist/pivot.css"; + +/* 初始页面样式 */ +html, +body { + margin: 0; + padding: 0; + height: 100%; +} + +/* Pivot 容器样式 */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### 加载数据 {#load-data} + +要向 Pivot 提供数据,请准备数据集。创建 *src/app/pivot/data.ts* 并导出数据和字段元数据: + +~~~jsx title="data.ts" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 其他数据项 + ]; + + const fields: any = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 其他字段 + ]; + + return { dataset, fields }; +}; +~~~ + +打开 *src/app/pivot/pivot.component.ts*,导入 `getData`,并在 `ngOnInit()` 中应用数据集: + +~~~jsx {2,18,20-21} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { getData } from "./data"; // 导入数据 +import { Component, ElementRef, OnInit, ViewChild, OnDestroy, ViewEncapsulation } from '@angular/core'; + +@Component({ + encapsulation: ViewEncapsulation.None, + selector: "pivot", + styleUrls: ["./pivot.component.css"], + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + const { dataset, fields } = getData(); // 解包数据和字段元数据 + this._table = new Pivot(this.pivot_container.nativeElement, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 其他值 + ] + }, + // 其他配置属性 + }); + } + + ngOnDestroy(): void { + this._table.destructor(); + } +} +~~~ + +组件现已可以使用。挂载时,Pivot 将使用提供的数据进行渲染。完整的配置属性列表请参见 [Pivot API 文档](api/overview/properties-overview.md)。 + +#### 处理事件 {#handle-events} + +用户在 Pivot 中的操作会触发相应事件,您可以对这些事件进行订阅。完整的事件列表请参见 [事件概览](api/overview/events-overview.md)。 + +以下代码片段在 `ngOnInit` 中扩展了一个 `open-filter` 事件监听器,当用户打开过滤器时记录字段 ID: + +~~~jsx {18-20} title="pivot.component.ts" +// ... +ngOnInit() { + const { dataset, fields } = getData(); + this._table = new Pivot(this.pivot_container.nativeElement, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 其他值 + ] + } + }); + + this._table.api.on("open-filter", (ev) => { + console.log("The field id for which the filter is activated:", ev.id); + }); +} + +ngOnDestroy(): void { + this._table.destructor(); +} +~~~ + +### 第三步:将 Pivot 添加到应用 {#step-3-add-pivot-to-the-app} + +要将 `PivotComponent` 嵌入应用,请打开 *src/app/app.component.ts* 并将默认代码替换为以下内容: + +~~~jsx {5} title="app.component.ts" +import { Component } from "@angular/core"; + +@Component({ + selector: "app-root", + template: `` // 在 "pivot.component.ts" 文件中创建的模板 +}) +export class AppComponent { + name = ""; +} +~~~ + +然后创建 *src/app/app.module.ts* 并注册 `PivotComponent`: + +~~~jsx {4-5,8} title="app.module.ts" +import { NgModule } from "@angular/core"; +import { BrowserModule } from "@angular/platform-browser"; + +import { AppComponent } from "./app.component"; +import { PivotComponent } from "./pivot/pivot.component"; + +@NgModule({ + declarations: [AppComponent, PivotComponent], + imports: [BrowserModule], + bootstrap: [AppComponent] +}) +export class AppModule {} +~~~ + +最后,打开 *src/main.ts* 并将其内容替换为以下引导代码: + +~~~jsx title="main.ts" +import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; +import { AppModule } from "./app/app.module"; +platformBrowserDynamic() + .bootstrapModule(AppModule) + .catch((err) => console.error(err)); +~~~ + +启动应用,查看 Pivot 在页面上渲染数据的效果。 + +![Pivot 初始化](../assets/trial_pivot.png) + +Pivot 现已与 Angular 集成完毕。您可以根据项目需求自定义配置。完整示例请参见 [**GitHub 上的 angular-pivot-demo**](https://github.com/DHTMLX/angular-pivot-demo)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-react.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-react.md new file mode 100644 index 0000000..57f36ab --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-react.md @@ -0,0 +1,289 @@ +--- +sidebar_label: 与 React 集成 +title: 与 React 集成 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解与 React 的集成方式。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费试用版。 +--- + +# 与 React 集成 {#integration-with-react} + +:::tip +本文假定您已熟悉 [**React**](https://react.dev) 的基本概念和模式。如需回顾,请参阅 [**React 文档**](https://react.dev/learn)。 +::: + +DHTMLX Pivot 可作为普通组件与 **React** 集成。完整的示例项目请参见 [**GitHub 上的 React Pivot 演示**](https://github.com/DHTMLX/react-pivot-demo)。 + +## 创建项目 {#create-a-project} + +:::info +开始前请先安装 [**Node.js**](https://nodejs.org/en/)。[**Vite**](https://vite.dev/) 为可选项。 +::: + +创建一个名为 *my-react-pivot-app* 的基础 **React** 项目(或基于 Vite 的项目)。 + +以下命令可引导创建一个 Create React App 项目: + +~~~bash +npx create-react-app my-react-pivot-app +~~~ + +### 安装依赖 {#install-dependencies} + +切换到新建的项目目录: + +~~~bash +cd my-react-pivot-app +~~~ + +使用包管理器安装依赖并启动开发服务器: + +- 使用 [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # 或:yarn dev +~~~ + +- 使用 [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +应用将运行在本地端口(例如 `http://localhost:3000`)。 + +## 创建 Pivot {#create-pivot} + +将 Pivot 包添加到项目中,然后将 Pivot 封装在 React 组件内。 + +### 第一步:安装包 {#step-1-install-the-package} + +下载 [**Pivot 试用包**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) 并按照 README 中的步骤操作。试用包有效期为 30 天。 + +### 第二步:创建组件 {#step-2-create-the-component} + +创建一个用于挂载 Pivot 的 React 组件。新建文件 *src/Pivot.jsx*。 + +#### 导入源文件 {#import-source-files} + +打开 *src/Pivot.jsx* 并导入 Pivot 源文件。导入路径取决于所使用的包版本: + +- **PRO 版本**(从本地文件夹安装): + +~~~jsx title="Pivot.jsx" +import { Pivot } from 'dhx-pivot-package'; +import 'dhx-pivot-package/dist/pivot.css'; +~~~ + +如果包中包含压缩资源,请导入 *pivot.min.css* 而非 *pivot.css*。 + +- **试用版本**: + +~~~jsx title="Pivot.jsx" +import { Pivot } from '@dhx/trial-pivot'; +import "@dhx/trial-pivot/dist/pivot.css"; +~~~ + +本教程使用 Pivot 的试用版本。 + +#### 设置容器并挂载 Pivot {#set-up-the-container-and-mount-pivot} + +要在页面上显示 Pivot,需创建一个容器 `div`,然后在 `useEffect` hook 中使用构造函数初始化 Pivot。 + +以下代码片段定义了一个最简的 Pivot React 组件: + +~~~jsx {2,6,9-10} title="Pivot.jsx" +import { useEffect, useRef } from "react"; +import { Pivot } from "@dhx/trial-pivot"; +import "@dhx/trial-pivot/dist/pivot.css"; // 引入 Pivot 样式 + +export default function PivotComponent(props) { + let container = useRef(); // Pivot 的容器 ref + + useEffect(() => { + // 初始化 Pivot 组件 + const table = new Pivot(container.current, {}); + + return () => { + table.destructor(); // 卸载时销毁 Pivot + }; + }, []); + + return
; +} +~~~ + +#### 添加样式 {#add-styles} + +为使 Pivot 正确渲染,请将以下样式添加到项目的主 CSS 文件中: + +~~~css title="index.css" +/* 初始页面的样式 */ +html, +body, +#root { + height: 100%; + padding: 0; + margin: 0; +} + +/* Pivot 容器的样式 */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### 加载数据 {#load-data} + +要向 Pivot 传入数据,需准备一个数据集。创建 *src/data.js* 并导出数据和字段元数据: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 其他数据项 + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 其他字段 + ]; + + return { dataset, fields }; +}; +~~~ + +打开 *src/App.js*,导入数据并将其作为 props 传递给 `` 组件: + +~~~jsx {2,5-6} title="App.js" +import Pivot from "./Pivot"; +import { getData } from "./data"; + +function App() { + const { fields, dataset } = getData(); + return ; +} + +export default App; +~~~ + +打开 *src/Pivot.jsx*,对 props 进行解构,并将其应用到 Pivot 的配置对象中: + +~~~jsx {5,10-11} title="Pivot.jsx" +import { useEffect, useRef } from "react"; +import { Pivot } from "@dhx/trial-pivot"; +import "@dhx/trial-pivot/dist/pivot.css"; + +export default function PivotComponent({ fields, dataset }) { + let container = useRef(); + + useEffect(() => { + const table = new Pivot(container.current, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 其他值 + ] + }, + // 其他配置属性 + }); + + return () => { + table.destructor(); + } + }, []); + + return
; +} +~~~ + +组件现已可以使用。挂载时,Pivot 将使用传入的数据进行渲染。完整的配置属性列表,请参见 [Pivot API 文档](api/overview/properties-overview.md)。 + +#### 处理事件 {#handle-events} + +用户在 Pivot 中的操作会触发相应事件,您可以订阅这些事件。完整的事件列表,请参见[事件概览](api/overview/events-overview.md)。 + +以下代码片段在 `useEffect` 中扩展了一个 `open-filter` 事件监听器,当用户打开过滤器时记录字段 ID: + +~~~jsx {19-21} title="Pivot.jsx" +// ... +useEffect(() => { + const table = new Pivot(container.current, { + fields, + data: dataset, + config: { + rows: ["state", "product_type"], + columns: ["product_line", "type"], + values: [ + { + field: "profit", + method: "sum" + }, // 其他值 + ] + }, + // 其他配置属性 + }); + + table.api.on("open-filter", (ev) => { + console.log("激活过滤器的字段 id:", ev.id); + }); + + return () => { + table.destructor(); + } +}, []); +// ... +~~~ + +启动应用,即可看到 Pivot 在页面上渲染数据。 + +![Pivot 初始化](../assets/trial_pivot.png) + +Pivot 现已成功与 React 集成。可根据项目需求自定义配置。完整示例请参见 [**GitHub 上的 react-pivot-demo**](https://github.com/DHTMLX/react-pivot-demo)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md new file mode 100644 index 0000000..f76d1f9 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md @@ -0,0 +1,302 @@ +--- +sidebar_label: 与 Svelte 集成 +title: 与 Svelte 集成 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解与 Svelte 的集成方式。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 30 天免费评估版 DHTMLX Pivot。 +--- + +# 与 Svelte 集成 {#integration-with-svelte} + +:::tip +本文假设您已熟悉 **Svelte** 的基本概念和模式。如需回顾,请参阅 [**Svelte 文档**](https://svelte.dev/)。 +::: + +DHTMLX Pivot 可作为普通组件与 **Svelte** 集成。完整的可运行示例请参见 [**GitHub 上的 Svelte Pivot 演示**](https://github.com/DHTMLX/svelte-pivot-demo)。 + +## 创建项目 {#create-a-project} + +:::info +开始前请先安装 [**Node.js**](https://nodejs.org/en/)。[**Vite**](https://vite.dev/) 为可选项。 +::: + +以下命令将运行 Vite 项目脚手架工具,并允许您选择 Svelte 模板: + +~~~bash +npm create vite@latest +~~~ + +将项目命名为 *my-svelte-pivot-app*。 + +### 安装依赖 {#install-dependencies} + +切换至新建的项目目录: + +~~~bash +cd my-svelte-pivot-app +~~~ + +使用包管理器安装依赖并启动开发服务器: + +- 使用 [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # 或:yarn dev +~~~ + +- 使用 [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +应用将在本地端口运行(例如 `http://localhost:3000`)。 + +## 创建 Pivot {#create-pivot} + +将 Pivot 包添加到项目中,然后将 Pivot 封装为 Svelte 组件。 + +### 第一步:安装包 {#step-1-install-the-package} + +下载 [**Pivot 试用包**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) 并按照 README 中的步骤操作。试用版 Pivot 包有效期为 30 天。 + +### 第二步:创建组件 {#step-2-create-the-component} + +创建一个挂载 Pivot 的 Svelte 组件。新建文件 *src/Pivot.svelte*。 + +#### 导入源文件 {#import-source-files} + +打开 *src/Pivot.svelte* 并导入 Pivot 源文件。导入路径取决于包的版本: + +- **PRO 版本**(从本地文件夹安装): + +~~~html title="Pivot.svelte" + +~~~ + +如果包附带压缩资源,请将 *pivot.css* 替换为 *pivot.min.css*。 + +- **试用版本**: + +~~~html title="Pivot.svelte" + +~~~ + +本教程使用 Pivot 的试用版本。 + +#### 设置容器并挂载 Pivot {#set-up-the-container-and-mount-pivot} + +要在页面上显示 Pivot,请添加一个容器 `div`,然后在 `onMount` 生命周期钩子中使用构造函数初始化 Pivot,并在 `onDestroy` 钩子中销毁 Pivot。 + +以下代码片段定义了一个最简 Pivot Svelte 组件: + +~~~html {3,6,10-11,19} title="Pivot.svelte" + + +
+~~~ + +#### 添加样式 {#add-styles} + +要使 Pivot 正确渲染,请将以下样式添加到项目的主 CSS 文件中: + +~~~css title="main.css" +/* 初始页面的样式 */ +html, +body, +#app { /* 使用 #app 根容器 */ + height: 100%; + padding: 0; + margin: 0; +} + +/* Pivot 容器的样式 */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### 加载数据 {#load-data} + +要向 Pivot 传入数据,请准备一个数据集。创建 *src/data.js* 并导出数据和字段元数据: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 其他数据项 + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 其他字段 + ]; + + return { dataset, fields }; +}; +~~~ + +打开 *src/App.svelte*,导入数据并将其作为 props 传递给新的 `` 组件: + +~~~html {3,5,8} title="App.svelte" + + + +~~~ + +打开 *src/Pivot.svelte*,使用 `export let` 声明传入的 props,并将其应用到 Pivot 配置对象中: + +~~~html {6-7,14-15} title="Pivot.svelte" + + +
+~~~ + +组件现已准备好使用。挂载时,Pivot 将使用所提供的数据进行渲染。完整的配置属性列表请参见 [Pivot API 文档](api/overview/properties-overview.md)。 + +#### 处理事件 {#handle-events} + +用户在 Pivot 中的操作会触发可订阅的事件。完整的事件列表请参见 [事件概览](api/overview/events-overview.md)。 + +以下代码片段在 `onMount` 中扩展了一个 `open-filter` 事件监听器,当用户打开筛选器时记录字段 ID: + +~~~html {22-24} title="Pivot.svelte" + + +// ... +~~~ + +启动应用,即可看到 Pivot 在页面上渲染数据。 + +![Pivot 初始化](../assets/trial_pivot.png) + +Pivot 现已与 Svelte 集成完成。您可以根据项目需求自定义配置。完整示例请参见 [**GitHub 上的 svelte-pivot-demo**](https://github.com/DHTMLX/svelte-pivot-demo)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md new file mode 100644 index 0000000..9d1d881 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md @@ -0,0 +1,312 @@ +--- +sidebar_label: 与 Vue 集成 +title: 与 Vue 集成 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解与 Vue 的集成方式。浏览开发指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# 与 Vue 集成 {#integration-with-vue} + +:::tip +本文假设您已具备 [**Vue**](https://vuejs.org/) 基本概念和模式的相关知识。如需复习,请参阅 [**Vue 3 文档**](https://vuejs.org/guide/introduction.html#getting-started)。 +::: + +DHTMLX Pivot 可作为普通组件与 **Vue** 集成。完整的工作示例请参见 [**GitHub 上的 Vue Pivot 演示**](https://github.com/DHTMLX/vue-pivot-demo)。 + +## 创建项目 {#create-a-project} + +:::info +开始之前,请先安装 [**Node.js**](https://nodejs.org/en/)。 +::: + +以下命令将运行官方的 **Vue** 项目脚手架工具: + +~~~bash +npm create vue@latest +~~~ + +该命令会安装并执行 `create-vue`。详情请参阅 [Vue.js 快速入门](https://vuejs.org/guide/quick-start.html#creating-a-vue-application)。 + +将项目命名为 *my-vue-pivot-app*。 + +### 安装依赖 {#install-dependencies} + +进入新建的项目目录: + +~~~bash +cd my-vue-pivot-app +~~~ + +使用您的包管理器安装依赖并启动开发服务器: + +- 使用 [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # 或:yarn dev +~~~ + +- 使用 [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +应用将运行在本地端口上(例如 `http://localhost:3000`)。 + +## 创建 Pivot {#create-pivot} + +将 Pivot 包添加到项目中,然后将 Pivot 封装为一个 Vue 组件。 + +### 第一步:安装包 {#step-1-install-the-package} + +下载 [**Pivot 试用包**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) 并按照 README 中的步骤操作。Pivot 试用包有效期为 30 天。 + +### 第二步:创建组件 {#step-2-create-the-component} + +创建一个用于挂载 Pivot 的 Vue 组件。新建文件 *src/components/Pivot.vue*。 + +#### 导入源文件 {#import-source-files} + +打开 *src/components/Pivot.vue* 并导入 Pivot 源文件。导入路径取决于所使用的包版本: + +- **PRO 版本**(从本地文件夹安装): + +~~~html title="Pivot.vue" + +~~~ + +如果包附带的是压缩资源,请导入 *pivot.min.css* 而非 *pivot.css*。 + +- **试用版本**: + +~~~html title="Pivot.vue" + +~~~ + +本教程使用 Pivot 的试用版本。 + +#### 设置容器并挂载 Pivot {#set-up-the-container-and-mount-pivot} + +要在页面上显示 Pivot,需添加一个容器 `div`,然后在 `mounted` 钩子中使用构造函数初始化 Pivot,并在 `unmounted` 钩子中销毁 Pivot。 + +以下代码片段定义了一个最简化的 Pivot Vue 组件: + +~~~html {2,7-8,18} title="Pivot.vue" + + + +~~~ + +#### 添加样式 {#add-styles} + +为确保 Pivot 正确渲染,请将以下样式添加到项目的主 CSS 文件中: + +~~~css title="style.css" +/* 初始页面的样式 */ +html, +body, +#app { /* 使用 #app 根容器 */ + height: 100%; + padding: 0; + margin: 0; +} + +/* Pivot 容器的样式 */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### 加载数据 {#load-data} + +要向 Pivot 传入数据,需准备一个数据集。创建 *src/data.js* 并导出数据及字段元数据: + +~~~jsx title="data.js" +export function getData() { + const dataset = [ + { + "cogs": 51, + "date": "10/1/2018", + "inventory_margin": 503, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 46, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Lemon", + "profit": -5, + "sales": 122, + "state": "Colorado", + "expenses": 76, + "type": "Decaf" + }, + { + "cogs": 52, + "date": "10/1/2018", + "inventory_margin": 405, + "margin": 71, + "market_size": "Major Market", + "market": "Central", + "marketing": 17, + "product_line": "Leaves", + "product_type": "Herbal Tea", + "product": "Mint", + "profit": 26, + "sales": 123, + "state": "Colorado", + "expenses": 45, + "type": "Decaf" + }, // 其他数据项 + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // 其他字段 + ]; + + return { dataset, fields }; +}; +~~~ + +打开 *src/App.vue*,导入数据并通过 `data()` 选项暴露数据,然后将值作为 props 传递给新的 `` 组件: + +~~~html {3,7-13,18} title="App.vue" + + + +~~~ + +打开 *src/components/Pivot.vue*,声明传入的 props 并将其应用到 Pivot 配置对象中: + +~~~html {6,10-11} title="Pivot.vue" + + + +~~~ + +组件现已可以使用。挂载后,Pivot 将使用所提供的数据进行渲染。完整的配置属性列表,请参阅 [Pivot API 文档](api/overview/properties-overview.md)。 + +#### 处理事件 {#handle-events} + +用户在 Pivot 中的操作会触发相应的事件,您可以订阅这些事件。完整的事件列表,请参阅[事件概览](api/overview/events-overview.md)。 + +以下代码片段在 `mounted` 中添加了一个 `open-filter` 事件监听器,当用户打开筛选器时,它会记录对应的字段 ID: + +~~~html {22-24} title="Pivot.vue" + + +// ... +~~~ + +启动应用,即可看到 Pivot 在页面上渲染数据。 + +![Pivot 初始化](../assets/trial_pivot.png) + +Pivot 现已与 Vue 完成集成。您可以根据项目需求自定义配置。完整示例请参见 [**GitHub 上的 vue-pivot-demo**](https://github.com/DHTMLX/vue-pivot-demo)。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/loading-data.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/loading-data.md new file mode 100644 index 0000000..2a04cd5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/loading-data.md @@ -0,0 +1,279 @@ +--- +sidebar_label: 加载数据 +title: 加载数据 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解如何加载数据。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 加载数据 {#loading-data} + +Pivot 通过 [`data`](api/config/data-property.md) 属性接受 JSON 格式的数据。Pivot 也支持将 CSV 数据转换为 JSON 后再加载。 + +## 准备加载数据 {#prepare-data-for-loading} + +[`data`](api/config/data-property.md) 属性接受一个对象数组,其中每个对象代表一行数据。每个对象的键定义了 Pivot 表中使用的维度和值。 + +以下代码片段定义了一个示例 `data` 数组: + +~~~jsx +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + { + name: "Argentina", + year: 2017, + continent: "South America", + form: "Republic", + gdp: 212.507, + oil: 1.732, + balance: 7.167, + when: new Date("1/15/2017") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 260.071, + oil: 2.845, + balance: 6.728, + when: new Date("6/16/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 324.405, + oil: 4.333, + balance: 5.99, + when: new Date("2/20/2014") + }, + { + name: "Argentina", + year: 2014, + continent: "South America", + form: "Republic", + gdp: 305.763, + oil: 2.626, + balance: 7.544, + when: new Date("8/17/2014") + }, + // 其他数据 +]; +~~~ + +:::info +有关定义字段和 Pivot 结构的信息,请参阅[数据操作](guides/working-with-data.md)。 +::: + +## 从文件加载数据 {#load-data-from-a-file} + +Pivot 在初始化后从外部文件加载 JSON 数据。请准备一个包含数据、字段和配置的源文件。 + +以下代码片段在单独的文件中定义了 `data`、`fields` 以及 `getData()` 访问器: + +~~~jsx +function getData() { + return { + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"], + } + } + }, + fields + }; +} +const fields = [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } +]; + +const data = [ + { + name: "Argentina", + year: 2015, + continent: "South America", + form: "Republic", + gdp: 181.357, + oil: 1.545, + balance: 4.699, + when: new Date("4/21/2015") + }, + // 其他数据 +]; +~~~ + +在页面标记中添加源数据文件的路径: + +~~~html title="index.html" + + + + +~~~ + +以下代码片段创建 Pivot 并从准备好的文件中加载数据: + +~~~jsx +const { data, config, fields } = getData(); +const table = new pivot.Pivot("#root", { data, config, fields }); +~~~ + +## 从服务器加载数据 {#load-data-from-a-server} + +要从服务器端点加载数据,请使用原生 `fetch` 方法(或任何等效方法)发送请求,然后将响应传递给 [`setConfig`](api/methods/setconfig-method.md),该方法会更新 Pivot 配置并保留之前设置的选项。 + +以下代码片段以空数据初始化 Pivot,从服务器获取数据和字段,然后通过 `setConfig` 应用它们: + +~~~jsx +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +Promise.all([ + fetch(server + "/data").then((res) => res.json()), + fetch(server + "/fields").then((res) => res.json()) +]).then(([data, fields]) => { + table.setConfig({ data, fields }); +}); +~~~ + +有关更多信息,请参阅以下主题:[与服务器协作](/guides/working-with-server) + +## 加载 CSV 数据 {#load-csv-data} + +Pivot 支持通过外部 JS 解析库将 CSV 数据转换为 JSON 后再加载。转换后的数据与原生 JSON 的行为相同。 + +以下示例使用外部 [PapaParse](https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js) 库在点击按钮时加载并转换数据。`convert()` 辅助函数接受以下参数: + +- `data` — 包含 CSV 数据的字符串 +- `headers` — CSV 字段名称的数组 +- `meta` — 将字段名称映射到数据类型的对象 + +以下代码片段创建 Pivot,定义 `convert()` 辅助函数,并在点击按钮时通过 [`setConfig`](api/methods/setconfig-method.md) 应用解析后的 CSV 数据: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +function convert(data, headers, meta) { + const header = headers.join(",") + "\n"; + const processedData = header + data; + + return Papa.parse(processedData, { + header: true, + dynamicTyping: true, + transform: (v, f) => { + return meta && meta[f] === "date" ? new Date(v) : v; + } + }); +} + +function fromCSV() { + const fields = [ + { id: "name", label: "Name", type: "text" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "gdp", label: "GDP", type: "number" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" }, + { id: "year", label: "Year", type: "number" }, + { id: "when", label: "When", type: "date" } + ]; + + const config = { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }; + + const headers = [ + "name", + "year", + "continent", + "form", + "gdp", + "oil", + "balance", + "when" + ]; + + // 显式标记日期字段以进行正确转换 + const meta = { when: "date" }; + + const dataURL = "https://some-backend-url"; + fetch(dataURL) + .then(response => response.text()) + .then(text => convert(text, headers, meta)) + .then(data => { + table.setConfig({ + data: data.data, + fields, + config + }); + }); +} + +const importButton = document.createElement("button"); +importButton.addEventListener("click", fromCSV); +importButton.textContent = "Import"; + +document.body.appendChild(importButton); +~~~ + +## 示例 {#example} + +以下代码片段演示了如何加载 JSON 和 CSV 数据: + + + +**相关示例**: +- [Pivot 2. 日期格式](https://snippet.dhtmlx.com/shn1l794) +- [Pivot 2. 不同数据集](https://snippet.dhtmlx.com/6xtqge4i) +- [Pivot 2. 大型数据集](https://snippet.dhtmlx.com/e6qwqrys) + +**相关文章**:[日期格式化](guides/localization.md#date-formatting) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/localization.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/localization.md new file mode 100644 index 0000000..8e223cd --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/localization.md @@ -0,0 +1,293 @@ +--- +sidebar_label: 本地化 +title: 本地化 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解本地化相关内容。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 本地化 {#localization} + +Pivot 支持对界面中的所有标签进行本地化。您可以创建新的语言区域设置,或修改内置区域设置,然后通过 [`locale`](api/config/locale-property.md) 属性或 [`setLocale`](api/methods/setlocale-method.md) 方法将其应用到 Pivot。 + +## 默认区域设置 {#default-locale} + +Pivot 默认使用英语区域设置。以下代码片段展示了内置 `en` 区域设置的结构: + +~~~jsx +const en = { + // pivot + pivot: { + sum: "Sum", + min: "Min", + max: "Max", + count: "Count", + counta: "CountA", + countunique: "CountUnique", + average: "Average", + median: "Median", + product: "Product", + stdev: "StDev", + stdevp: "StDevP", + var: "Var", + varp: "VarP", + "Raw date": "Raw date", + "Raw number": "Raw number", + "Raw text": "Raw text", + Year: "Year", + Month: "Month", + Day: "Day", + Hour: "Hour", + Minute: "Minute", + Total: "Total", + Values: "Values", + Rows: "Rows", + Columns: "Columns", + "Click on the plus icon(s) to add data": + "Click on the plus icon(s) to add data", + 'Click on "Show settings" to see the available configuration options': + 'Click on "Show settings" to see the available configuration options', + "Show settings": "Show settings", + "Hide settings": "Hide settings" + }, + + // query + query: { + "Add filter": "Add filter", + "Add Filter": "Add Filter", + "Add Group": "Add Group", + Edit: "Edit", + Delete: "Delete", + + "Select all": "Select all", + "Unselect all": "Unselect all", + + Cancel: "Cancel", + Apply: "Apply", + + and: "and", + or: "or", + in: "in", + + equal: "equal", + "not equal": "not equal", + contains: "contains", + "not contains": "not contains", + "begins with": "begins with", + "not begins with": "not begins with", + "ends with": "ends with", + "not ends with": "not ends with", + + greater: "greater", + "greater or equal": "greater or equal", + less: "less", + "less or equal": "less or equal", + between: "between", + "not between": "not between" + }, + + // calendar + calendar: { + monthFull: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December", + ], + monthShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ], + + dayFull: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + ], + + dayShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + hours: "Hours", + minutes: "Minutes", + done: "Done", + clear: "Clear", + today: "Today", + am: ["am", "AM"], + pm: ["pm", "PM"], + + weekStart: 7, + clockFormat: 24, + }, + + // core + core: { + ok: "OK", + cancel: "Cancel", + select: "Select", + "No data": "No data" + }, + + // formats + formats: { + dateFormat: "%d.%m.%Y", + timeFormat: "%H:%i" + }, + + lang: "en-US", +}; +~~~ + +## 应用区域设置 {#apply-a-locale} + +Pivot 通过 `pivot.locales` 对象提供三个内置区域设置:`en`、`de` 和 `cn`。在初始化时,将内置区域设置传入 [`locale`](api/config/locale-property.md) 属性即可。 + +以下代码片段展示了如何使用德语区域设置初始化 Pivot: + +~~~jsx +new pivot.Pivot("#root", { + // other properties + locale: pivot.locales.de, +}); +~~~ + +要应用自定义区域设置,请执行以下操作: + +- 创建一个区域设置对象(或修改内置区域设置),并为所有文本标签提供翻译(支持任何语言) +- 通过 [`locale`](api/config/locale-property.md) 属性或 [`setLocale`](api/methods/setlocale-method.md) 方法将区域设置应用到 Pivot + +以下代码片段创建了 Pivot,然后在运行时通过 `setLocale` 应用自定义的韩语区域设置: + +~~~jsx +// create Pivot +const widget = new pivot.Pivot("#root", { + data, + // other configuration properties +}); + +const ko = { /* object with locale */ }; +widget.setLocale(ko); +~~~ + +:::tip +调用 [`setLocale`](api/methods/setlocale-method.md) 时不传参数(或传入 `null`)可将 Pivot 重置为默认的英语区域设置。 +::: + +## 格式化日期 {#date-formatting} + +Pivot 接受 `Date` 对象形式的日期。在将数据传入 Pivot 之前,请先将字符串值解析为 `Date` 对象。默认的 `dateFormat` 为 `"%d.%m.%Y"`,取自当前区域设置。 + +若要更改所有日期字段的格式,请在 [`locale`](api/config/locale-property.md) 属性的 `formats` 对象中设置新的 `dateFormat` 值。 + +以下代码片段将字符串日期解析为 `Date` 对象,然后使用自定义 `dateFormat` 初始化 Pivot,并在运行时通过 `setConfig` 更新格式: + +~~~jsx {17} +function setFormat(value) { + table.setConfig({ locale: { formats: { dateFormat: value } } }); +} + +// convert date strings to Date objects +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + locale: { formats: { dateFormat: "%d %M %Y %H:%i" } }, + fields, + data: dataset, + config: { + rows: ["state"], + columns: ["product_line", "product_type"], + values: [ + { + field: "date", + method: "min" + }, + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + } + ] + } +}); +~~~ + +要为特定字段设置自定义格式,请使用 [`fields`](api/config/fields-property.md) 属性的 `format` 参数。请参阅[为字段应用格式](guides/working-with-data.md#applying-formats-to-fields)。 + +## 日期和时间格式字符 {#date-and-time-format-characters} + +Pivot 使用以下字符定义日期和时间格式: + +| 字符 | 含义 | 示例 | +| :-------- | :------------------------------------------------ |:------------------------| +| %d | 带前导零的日期数字 | 从 01 到 31 | +| %j | 不带前导零的日期数字 | 从 1 到 31 | +| %D | 星期的缩写名称 | Su Mo Tu Sat | +| %l | 星期的完整名称 | Sunday Monday Tuesday | +| %W | 带前导零的周数(以周一为一周的第一天) | 从 01 到 52/53 | +| %m | 带前导零的月份数字 | 从 01 到 12 | +| %n | 不带前导零的月份数字 | 从 1 到 12 | +| %M | 月份的缩写名称 | Jan Feb Mar | +| %F | 月份的完整名称 | January February March | +| %y | 两位数年份 | 24 | +| %Y | 四位数年份 | 2024 | +| %h | 带前导零的 12 小时制小时数 | 从 01 到 12 | +| %g | 不带前导零的 12 小时制小时数 | 从 1 到 12 | +| %H | 带前导零的 24 小时制小时数 | 从 00 到 23 | +| %G | 不带前导零的 24 小时制小时数 | 从 0 到 23 | +| %i | 带前导零的分钟数 | 从 01 到 59 | +| %s | 带前导零的秒数 | 从 01 到 59 | +| %S | 毫秒数 | 128 | +| %a | am 或 pm | am(午夜到正午)和 pm(正午到午夜)| +| %A | AM 或 PM | AM(午夜到正午)和 PM(正午到午夜)| +| %c | 以 ISO 8601 格式显示日期和时间 | 2024-10-04T05:04:09 | + +要将 2024 年 9 月 20 日 16:47:08.128 表示为 *2024-09-20 16:47:08.128*,请使用格式 `"%Y-%m-%d %H:%i:%s.%S"`。 + +## 格式化数字 {#number-formatting} + +Pivot 根据当前区域设置的 `lang` 值对所有 `number` 类型字段进行本地化处理。该 widget 遵循 [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) 规范。默认设置将小数位数限制为 3 位,并对整数部分应用千位分隔符。 + +若要跳过对特定数字字段的格式化,或设置自定义格式,请使用 [`fields`](api/config/fields-property.md) 属性的 `format` 参数。将 `format` 设置为 `false` 可禁用格式化,也可将其设置为包含格式配置的对象(请参阅[为字段应用格式](guides/working-with-data.md#applying-formats-to-fields))。 + +以下代码片段禁用了 `year` 字段的数字格式化: + +~~~jsx +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +## 示例 {#example} + +以下代码片段演示了在多个区域设置之间切换: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/stylization.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/stylization.md new file mode 100644 index 0000000..544a596 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/stylization.md @@ -0,0 +1,266 @@ +--- +sidebar_label: 样式 +title: 样式 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解有关样式的相关内容。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载免费的 30 天评估版 DHTMLX Pivot。 +--- + +# 样式 {#styling} + +Pivot 内置了默认主题,并提供 CSS 变量和工具类以供自定义。在 widget 容器(或任意祖先元素)上覆盖这些变量,即可更改颜色、边框等视觉属性。 + +## 默认样式 {#default-style} + +Pivot 的默认主题为 **Material**。以下 CSS 代码片段展示了 Material 主题在 widget 容器上设置的变量: + +~~~css +.wx-material-theme { + --wx-theme-name: material; + --wx-pivot-primary-hover: #194e9e; + --wx-pivot-border-color: var(--wx-color-font-disabled); + --wx-pivot-field-hover: linear-gradient( + rgba(0, 0, 0, 0.1) 0%, + rgba(0, 0, 0, 0.1) 100% + ); +} +~~~ + +:::tip 注意 +未来版本的 Pivot 可能会重命名 CSS 变量。升级后请检查变量名称,并在代码中更新,以避免显示问题。 +::: + +## 内置主题 {#built-in-theme} + +Pivot 提供一个内置主题:**Material**。可通过向 widget 容器添加主题类,或在页面中引入预构建的皮肤样式表来应用该主题。 + +以下代码片段通过向 widget 容器添加 `wx-material-theme` 类来应用 Material 主题: + +~~~html {} + +
+~~~ + +以下代码片段直接引入 Material 皮肤样式表: + +~~~html {} + +~~~ + +## 自定义内置主题 {#customize-built-in-theme} + +在 `.wx-material-theme` 选择器上覆盖 Material 主题变量,即可更改颜色、边框等视觉属性。 + +以下示例通过覆盖 Material 主题变量,将 Pivot 渲染为深色配色方案: + +~~~html + + +~~~ + +## 自定义样式 {#custom-style} + +通过在应用于 widget 容器的自定义类上覆盖 CSS 变量,来更改 Pivot 的外观。 + +以下示例通过 `.demo` 类为 Pivot 应用自定义样式: + +~~~html +
+ +~~~ + +## 滚动条样式 {#scroll-style} + +使用 `.wx-styled-scroll` CSS 类为 Pivot 滚动条应用自定义样式。使用前请检查浏览器兼容性:[caniuse: CSS Scrollbar](https://caniuse.com/css-scrollbar)。 + +以下代码片段在 widget 容器上启用自定义滚动条样式: + +~~~html {} title="index.html" + +
+~~~ + +## 单元格样式 {#cell-style} + +若要为正文或页脚单元格设置样式,请使用 [`tableShape`](api/config/tableshape-property.md) 属性的 `cellStyle` 参数。若要为表头单元格设置样式,请使用 [`headerShape`](api/config/headershape-property.md) 属性的 `cellStyle` 参数。两种情况下,`cellStyle` 函数均返回一个 CSS 类名,Pivot 会将其应用于对应单元格。 + +以下示例为正文和表头单元格应用样式: + +- 正文单元格根据单元格值(例如 `status` 字段中的 `"Down"`、`"Up"`、`"Idle"`)以及汇总值(大于 40 或小于 5)接收相应类名 +- 表头单元格根据 `streaming` 字段的值接收类名——值为 `"no"` 时使用 `status-down`,其他值使用 `status-up` + +~~~jsx +const widget = new pivot.Pivot("#pivot", { + tableShape: { + totalColumn: true, + totalRow:true, + cellStyle: (field, value, area, method, isTotal) => { + if (field === "status" && area === "rows" && value) { + if (value === "Down") { + return "status-down"; + } else if (value === "Up") { + return "status-up"; + } else if (value === "Idle") { + return "status-idle"; + } + } + if(isTotal ==="column" && area == "values"){ + if(value > 40) + return "status-up"; + else if (value < 5) + return "status-down"; + } + } + }, + headerShape:{ + cellStyle:(field, value, area, method, isTotal) => { + if(field == "streaming") + return value ==="no"?"status-down":"status-up"; + } + }, + fields, + data: dataset, + config: { + rows: [ + "protocol", + "status", + ], + columns: [ + "streaming" + ], + values: [ + { + field: "id", + method: "count" + } + ] + } +}); +~~~ + +## 标记单元格中的值 {#mark-values-in-cells} + +使用 [`tableShape`](api/config/tableshape-property.md) 属性的 `marks` 参数,对满足条件的单元格应用 CSS 类。`marks` 中的每个条目将 CSS 类名(键)与规则(值)配对。 + +规则可以是预定义字符串(`"max"` 或 `"min"`),也可以是自定义函数 `(value, columnData, rowData) => boolean`。当函数返回 `true` 时,Pivot 会将该 CSS 类添加到对应单元格。 + +在应用 `marks` 之前,请先在样式表中创建相应的 CSS 类。 + +以下示例高亮显示最小值和最大值所在的单元格,并使用自定义函数标记大于 2 的非整数值: + +~~~jsx {18-26} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + tableShape: { + marks: { + // 内置标记(最小值/最大值高亮) + min_cell: "min", + max_cell: "max", + // 自定义标记 + g_avg: v => (v % 1 !== 0) && v > 2 + } + } +}); +~~~ + +以下代码片段定义了上述 `marks` 对象所引用的 CSS 类: + +~~~html title="index.html" + +~~~ + +## 特定 CSS 类 {#specific-css-classes} + +Pivot 内置了若干工具 CSS 类,您可以覆盖它们以对表格元素进行精细控制。 + +Pivot 通过内置的 `.wx-number` CSS 类将正文单元格中的数字右对齐。树形模式下(在 [`tableShape`](api/config/tableshape-property.md) 中设置 `tree: true` 时)的层级列除外。若要重置默认的数字对齐方式,请覆盖该类。 + +以下代码片段将正文单元格中的数字左对齐: + +~~~html + +~~~ + +若要为汇总列设置样式,请覆盖 `.wx-total` CSS 类。 + +以下代码片段为汇总单元格设置浅色背景和较粗的字体粗细: + +~~~html + +~~~ + +## 示例 {#example} + +以下代码片段为 Pivot 应用自定义样式: + + + +**相关示例**: + +- [Pivot 2. 汇总列的样式(自定义 CSS)](https://snippet.dhtmlx.com/9lkdbzmm) +- [Pivot 2. 单元格的最小值/最大值与自定义标记(条件格式)](https://snippet.dhtmlx.com/4cm4asbd) +- [Pivot 2. 交替行颜色(条纹行/斑马线)](https://snippet.dhtmlx.com/0cm0uko2) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/typescript-support.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/typescript-support.md new file mode 100644 index 0000000..a4d8209 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/typescript-support.md @@ -0,0 +1,17 @@ +--- +sidebar_label: TypeScript 支持 +title: TypeScript 支持 +description: 您可以在文档中了解如何在 DHTMLX JavaScript Pivot 库中使用 TypeScript。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 免费 30 天评估版本。 +--- + +# TypeScript 支持 {#typescript-support} + +DHTMLX Pivot 从 v2.0 起内置 TypeScript 类型定义,无需额外配置即可直接使用。 + +:::info +在 [Snippet Tool](https://snippet.dhtmlx.com/y2buoahe) 中在线体验 Pivot。 +::: + +## TypeScript 的优势 {#advantages-of-typescript} + +类型检查和自动补全能够在早期发现错误,内置的类型定义可以清晰地告知您 DHTMLX Pivot API 所期望的数据类型。 diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/working-with-data.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/working-with-data.md new file mode 100644 index 0000000..f7efc2b --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/working-with-data.md @@ -0,0 +1,687 @@ +--- +sidebar_label: 数据处理 +title: 数据处理 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解如何处理数据。浏览开发指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 数据处理 + +本页介绍如何在 Pivot 中对数据进行聚合、格式化、排序、筛选和预处理。有关加载和导出数据的说明,请参阅[加载数据](guides/loading-data.md)和[导出数据](guides/exporting-data.md)。 + +## 定义字段 {#define-fields} + +使用 [`fields`](api/config/fields-property.md) 属性声明 Pivot 可放置在行、列和值中的字段。`fields` 数组中的每个条目描述一个字段——其 ID、标签和数据类型。 + +以下代码片段使用五个字段初始化 Pivot: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields: [ + { id: "year", label: "Year", type: "number" }, + { id: "continent", label: "Continent", type: "text" }, + { id: "form", label: "Form", type: "text" }, + { id: "oil", label: "Oil", type: "number" }, + { id: "balance", label: "Balance", type: "number" } + ], + data, + config: {...} +}); +~~~ + +## 为字段应用格式 {#applying-formats-to-fields} + +Pivot 根据当前语言环境对数字和日期字段应用默认格式。详情请参阅[日期格式化](guides/localization.md#date-formatting)和[数字格式化](guides/localization.md#number-formatting)。 + +要覆盖特定字段的默认格式,请设置 [`fields`](api/config/fields-property.md) 属性的 `format` 参数。 + +### 格式化数字字段 {#format-numeric-fields} + +使用 `prefix` 和 `suffix` 在数值前后添加文本,并使用 `maximumFractionDigits` 控制小数精度。例如,要将 `12.345` 渲染为 `"12.35 EUR"`,请将 suffix 设置为 `" EUR"`,并将 `maximumFractionDigits` 设置为 `2`: + +~~~js +const fields = [ + { id: "sales", type: "number", format: { suffix: " EUR", maximumFractionDigits: 2 } }, +]; +~~~ + +默认格式将数字字段限制为 3 位小数,并对整数部分应用分组分隔符。要完全禁用格式化,请将 `format` 设置为 `false`: + +~~~js +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +以下示例将 `marketing`、`profit` 和 `sales` 标记为带有 `$` 前缀和固定 2 位小数的货币字段: + +~~~jsx +// 使用预定义数据集和字段初始化 Pivot +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { field: "marketing", method: "sum" }, + // other values + + ], + }, + fields:[ + // 自定义格式 + { id: "marketing", label: "Marketing", type:"number", format:{ + prefix: "$", minimumFractionDigits: 2, maximumFractionDigits: 2 } + } + ] +}); +~~~ + +### 格式化日期字段 {#format-date-fields} + +要覆盖单个字段的全局 `dateFormat`,请将 [`fields`](api/config/fields-property.md) 的 `format` 参数设置为日期格式字符串。 + +以下代码片段将 `"%M %d, %Y"` 设置为 `date` 字段的格式: + +~~~jsx +const fields = [ + { id: "date", type: "date", format: "%M %d, %Y" }, +]; +~~~ + +以下示例将字符串日期转换为 `Date` 对象,然后使用格式 `"%d %M %Y %H:%i"` 初始化 `date` 字段的 Pivot。字段值渲染为诸如 `"24 April 2025 14:30"` 的标签。 + +~~~jsx +// 将日期字符串转换为 Date 对象 +const dateFields = fields.filter(f => f.type === "date"); +dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v === "string") { + item[f.id] = new Date(v); + } + }); +}); + +// 使用字段特定日期格式初始化 Pivot +new pivot.Pivot("#pivot", { + data, + config: { + rows: ["state"], + columns: ["product_type"], + values: [ + { field: "date", method: "min" }, + { field: "profit", method: "sum" }, + { field: "sales", method: "sum" } + ] + }, + fields:[ + // 自定义格式:日 月 年 时:分 + { id: "date", label: "Date", type: "date", format: "%d %M %Y %H:%i" } + ] +}); +~~~ + +:::note +对于 `xlsx` 导出格式,Pivot 以原始值导出日期和数字字段,并使用其默认格式(或通过 [`fields`](api/config/fields-property.md) 属性定义的格式)。如果为某个字段定义了模板(参见 [`tableShape`](api/config/tableshape-property.md) 属性),Pivot 将导出该模板生成的渲染值。如果同时设置了 `template` 和 `format`,则模板优先于格式。 +::: + +## 定义 Pivot 结构 {#define-pivot-structure} + +使用 [`config`](api/config/config-property.md) 属性声明哪些字段作为行、列和聚合值显示,以及如何筛选数据。`config` 属性没有预定义值——您必须设置它才能渲染任何数据。完整参数列表请参阅 [`config`](api/config/config-property.md) 参考。 + +以下代码片段将 `continent` 和 `name` 放在行中,`year` 放在列中,三个聚合放在值中,并对 `name` 添加筛选器: + +~~~jsx {4-18} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["continent", "name"], + columns: ["year"], + values: [ + "count(oil)", + { field: "oil", method: "sum" }, + { field: "gdp", method: "sum" } + ] + }, + fields, + filters: { + name: { + contains: "B" + } + } +}); +~~~ + +## 排序数据 {#sorting-data} + +Pivot 在聚合期间支持在所有三个区域(值、列、行)中进行排序。在 UI 中,用户单击列标题进行排序。 + +要设置默认排序,请使用 [`fields`](api/config/fields-property.md) 属性的 `sort` 参数。该参数接受 `"asc"`、`"desc"` 或自定义比较函数。 + +以下示例在 Pivot 上方渲染可单击的字段标签,并在单击时切换排序方向: + +~~~jsx +const bar = document.getElementById("bar"); + +let sorted = ["studio", "genre"]; +setFields(); +bar.addEventListener('click', (e) => switchSort(e.target.id), false); + +function setFields(){ + let html = ""; + let sortedFields = fields.filter(f => (sorted.indexOf(f.id) != -1)); + + sortedFields.forEach((f) =>{ + const order = f.sort || "asc"; + html += `
+ ${f.label} +
`; + }); + bar.innerHTML = html; +} + +function switchSort(id){ + fields.forEach(f => { + if(f.id == id){ + f.sort = f.sort != "desc" ? "desc" : "asc"; + } + }); + // 更新 Pivot 字段 + table.setConfig({ fields }); + // 刷新图标 + setFields(bar, fields); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: [ + "studio", + "genre" + ], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +UI 中的排序默认启用。要禁用它,请将 [`columnShape`](api/config/columnshape-property.md) 属性的 `sort` 参数设置为 `false`。 + +以下代码片段禁用 UI 排序: + +~~~jsx {19} +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + columnShape: { + sort: false + } +}); +~~~ + +## 筛选数据 {#filtering-data} + +Pivot 支持与字段数据类型绑定的筛选器。可以在初始化后通过 Pivot UI 设置筛选器,也可以通过 [`config`](api/config/config-property.md) 属性的 `filters` 对象以声明方式设置。 + +在 UI 中,筛选器以每个字段的下拉列表形式显示。 + +#### 筛选器类型 {#filter-types} + +Pivot 支持按数据类型划分的以下筛选条件: + +- 文本字段 — `equal`、`notEqual`、`contains`、`notContains`、`beginsWith`、`notBeginsWith`、`endsWith`、`notEndsWith`、`includes` +- 数字字段 — `equal`、`notEqual`、`greater`、`greaterOrEqual`、`less`、`lessOrEqual`、`contains`、`notContains`、`beginsWith`、`notBeginsWith`、`endsWith`、`notEndsWith` +- 日期字段 — `equal`、`notEqual`、`greater`、`greaterOrEqual`、`less`、`lessOrEqual`、`between`、`notBetween`、`includes` + +`includes` 规则将筛选器限制为一组特定的允许值。 + +#### 添加筛选器 {#add-a-filter} + +要声明筛选器,请将 `filters` 对象添加到 [`config`](api/config/config-property.md) 属性中,以字段 ID 为键。每个值是一个筛选条件对象。 + +以下代码片段应用两个筛选器——一个针对 `genre`(包含 `"D"` 的值,限制为 `"Drama"`),一个针对 `title`(包含 `"A"` 的值): + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ], + filters: { + genre: { + contains: "D", + includes: ["Drama"] + }, + title: { + // 另一个字段("title")的筛选器 + contains: "A" + } + } + } +}); +~~~ + +:::info +要通过 Table widget API 筛选数据,请使用 [`getTable`](api/methods/gettable-method.md) 方法访问 Table 实例,并使用 [`filter-rows`](api/table/filter-rows.md) 事件。 +::: + +## 限制加载的数据 {#limiting-loaded-data} + +为防止组件在非常大的数据集上挂起,请使用 [`limits`](api/config/limits-property.md) 属性限制最终数据集中的行数和列数。Pivot 在达到限制后中断渲染。默认上限为行 10000、列 5000。 + +:::note +限制适用于大型数据集。这些数值是近似值——Pivot 不保证精确的行/列数量。 +::: + +以下代码片段将数据集限制为 10 行和 3 列: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio"], + columns: ["genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + }, + limits: { rows: 10, columns: 3 } +}); +~~~ + +## 应用数学方法 {#applying-maths-methods} + +### 默认方法 {#default-methods} + +Pivot 包含以下内置聚合方法: + +- `sum`(仅限数值)— 对所有选定值求和;忽略空单元格、`TRUE` 等逻辑值和文本 +- `min`(数值和日期值)— 返回最小值;忽略空单元格、逻辑值和文本。如果输入不包含数字,则返回 `0` +- `max`(数值和日期值)— 返回最大值;忽略空单元格、逻辑值和文本。如果输入不包含数字,则返回 `0` +- `count`(数值、文本和日期值)— 计算非空白单元格数量;这是分配给每个新添加字段的默认方法 +- `countunique`(数值和文本值)— 计算输入中唯一值的数量 +- `average`(仅限数值)— 计算输入的算术平均值;忽略空单元格、逻辑值和文本。包含值为零的单元格 +- `counta`(数值、文本和日期值)— 计算所有非空白值,包括数字、日期和文本 +- `median`(仅限数值)— 返回输入的中位数 +- `product`(仅限数值)— 返回输入中所有数字的乘积 +- `stdev`(仅限数值)— 标准差,将输入视为较大集合的样本 +- `stdevp`(仅限数值)— 标准差,将输入视为整体总体 +- `var`(仅限数值)— 方差,将输入视为较大集合的样本 +- `varp`(仅限数值)— 方差,将输入视为整体总体 + +以下代码片段显示内置方法定义: + +~~~jsx +const defaultMethods = { + sum: { type: "number", label: "sum" }, + min: { type: ["number", "date"], label: "min" }, + max: { type: ["number", "date"], label: "max" }, + count: { + type: ["number", "date", "text"], + label: "count", + branchMath: "sum" + }, + counta: { + type: ["number", "date", "text"], + label: "counta", + branchMath: "sum" + }, + countunique: { + type: ["number", "text"], + label: "countunique", + branchMath: "sum" + }, + average: { type: "number", label: "average", branchMode: "raw" }, + median: { type: "number", label: "median", branchMode: "raw" }, + product: { type: "number", label: "product" }, + stdev: { type: "number", label: "stdev", branchMode: "raw" }, + stdevp: { type: "number", label: "stdevp", branchMode: "raw" }, + var: { type: "number", label: "var", branchMode: "raw" }, + varp: { type: "number", label: "varp", branchMode: "raw" } +}; +~~~ + +通过 [`config`](api/config/config-property.md) 属性的 `values` 参数应用默认方法。请参阅[定义值](#options-for-defining-values)。 + +以下代码片段将 `count` 分配给 `title` 字段,将 `max` 分配给 `score` 字段: + +~~~jsx +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + // 字段 id + field: "title", + // 方法 + method: "count" + }, + { + id: "score", + method: "max" + } + ] + } +}); +~~~ + +### 定义值 {#options-for-defining-values} + +`values` 中的每个条目可以用以下两种等效形式之一定义: + +- 形如 `"operation(fieldID)"` 的字符串 +- 对象 `{ field: string, method: string }`(两个字段均为必填) + +以下代码片段在同一个 `values` 数组中使用了两种形式: + +~~~jsx +values: [ + "sum(sales)", // 选项一 + { field: "sales", method: "sum" } // 选项二 +] +~~~ + +### 覆盖默认方法 {#override-the-default-method} + +对于每个新添加的字段,Pivot 会分配该数据类型的第一个可用方法。要更改此行为,请使用 [`api.intercept`](api/internal/intercept-method.md) 方法拦截 `add-field` 事件。 + +以下示例拦截 `add-field` 事件,并在添加数字字段时强制使用 `max` 方法: + +~~~jsx {20-27} +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count", + }, + { + field: "score", + method: "max", + }, + ], + }, +}); +// 覆盖新添加的数字字段的默认方法 +table.api.intercept("add-field", (ev) => { + const { fields } = table.api.getState(); + const type = fields.find((f) => f.id == ev.field).type; + + if (ev.area == "values" && type == "number") { + ev.method = "max"; + } +}); +~~~ + +### 添加自定义数学方法 {#add-custom-math-methods} + +要添加自定义聚合方法,请使用 [`methods`](api/config/methods-property.md) 属性。每个条目将方法名(键)与包含 `handler` 函数和元数据的配置对象配对。`handler` 接受一个值数组并返回单个聚合值。 + +以下示例添加了两个特定于日期的方法。`countunique_date` 通过数字时间戳计算不同日期数量。`average_date` 通过平均时间戳返回平均日期: + +~~~jsx +function countUnique(values, converter) { + const valueMap = {}; + return values.reduce((acc, d) => { + if (converter) d = converter(d); + if (!valueMap[d]) { + acc++; + valueMap[d] = true; + } + return acc; + }, 0); +} + +const methods = { + countunique_date: { + handler: values => countUnique(values, v => new Date(v).getTime()), + type: "date", + label: "CountUnique", + }, + average_date: { + type: "date", + label: "Average", + branchMode: "raw", + handler: values => { + if (!values.length) return null; + const sum = values.reduce((acc, d) => acc + d.getTime(), 0); + const avgTime = sum / values.length; + return new Date(avgTime); + } + } +}; + +// 对 "count" 和 "unique count" 结果显示整数 +const templates = {}; +fields.forEach(f => { + if (f.type == "number") + templates[f.id] = (v, method) => + v && method.indexOf("count") < 0 ? parseFloat(v).toFixed(3) : v; +}); + +// 将日期字符串转换为 Date 对象 +const dateFields = fields.filter(f => f.type == "date"); +if (dateFields.length) { + dataset.forEach(item => { + dateFields.forEach(f => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + tableShape: { templates }, + methods: { ...pivot.defaultMethods, ...methods }, + config:{ + rows: ["state"], + columns: [ + "product_line", + "product_type" + ], + values: [ + { + field: "sales", + method: "sum" + }, + { + field: "sales", + method: "count" + }, + { + field: "date", + method: "countunique_date" + }, + { + field: "date", + method: "average_date" + } + ] + } +}); +~~~ + +## 使用谓词处理数据 {#processing-data-with-predicates} + +谓词是预处理函数,在 Pivot 将原始字段数据用于行或列之前对其进行转换。例如,谓词可以在聚合之前按月对日期进行分组。 + +以下代码片段显示 Pivot 默认应用的内置日期谓词: + +~~~jsx +const defaultPredicates = { + year: { label: "Year", type: "date", filter: { type: "number" } }, + quarter: { label: "Quarter", type: "date", filter: { type: "tuple" } }, + month: { label: "Month", type: "date", filter: { type: "tuple" } }, + week: { label: "Week", type: "date", filter: { type: "tuple" } }, + day: { label: "Day", type: "date", filter: { type: "number" } }, + hour: { label: "Hour", type: "date", filter: { type: "number" } }, + minute: { label: "Minute", type: "date", filter: { type: "number" } } +}; +~~~ + +要添加自定义谓词,请配置 [`predicates`](api/config/predicates-property.md) 属性。每个条目将谓词 ID(键)与配置对象配对: + +- `type` — 此谓词接受的字段类型(`"number"`、`"date"`、`"text"` 或数组) +- `label` — 在行/列的 GUI 下拉列表中显示的谓词标签 +- `handler` — 转换值并返回处理结果的函数 +- `template` — 可选函数,控制处理后值的显示方式 +- `field` — 可选函数,将谓词限制为特定字段 +- `filter` — 可选筛选器配置,当筛选器类型应与 `type` 不同,或数据格式应与 `template` 不同时使用 + +要使用自定义谓词,请将其 ID 设置为应应用谓词的行或列的 `method`。 + +以下代码片段注册两个自定义谓词(`monthYear` 和 `profitSign`),并在 `columns` 配置中应用它们: + +~~~jsx +const predicates = { + monthYear: { + label: "Month-year", + type: "date", + handler: (d) => new Date(d.getFullYear(), d.getMonth(), 1), + template: (date, locale) => { + const months = locale.getRaw().calendar.monthFull; + return months[date.getMonth()] + " " + date.getFullYear(); + }, + }, + profitSign: { + label: "Profit Sign", + type: "number", + filter: { + type: "tuple", + format: (v) => (v < 0 ? "Negative" : "Positive"), + }, + field: (f) => f === "profit", + handler: (v) => (v < 0 ? -1 : 1), + template: (v) => (v < 0 ? "Negative profit" : "Positive profit"), + }, +}; + +// 将日期字符串转换为 Date 对象 +const dateFields = fields.filter((f) => f.type == "date"); +if (dateFields.length) { + dataset.forEach((item) => { + dateFields.forEach((f) => { + const v = item[f.id]; + if (typeof v == "string") item[f.id] = new Date(v); + }); + }); +} + +const table = new pivot.Pivot("#pivot", { + fields, + data: dataset, + predicates: { ...pivot.defaultPredicates, ...predicates }, + tableShape: { tree: true }, + config: { + rows: ["product_type", "product"], + columns: [ + { field: "profit", method: "profitSign" }, + { field: "date", method: "monthYear" }, + ], + values: ["sales", "expenses"], + }, +}); +~~~ + +## 添加包含汇总值的列和行 {#add-columns-and-rows-with-total-values} + +使用 [`tableShape`](api/config/tableshape-property.md) 属性在右侧渲染汇总列(`totalColumn: true`)或汇总页脚行(`totalRow: true`)。 + +以下代码片段同时启用汇总列和汇总行: + +~~~jsx {2-5} +const table = new pivot.Pivot("#root", { + tableShape: { + totalRow: true, + totalColumn: true + }, + fields, + data, + config: { + rows: ["studio"], + columns: ["type"], + values: [ + { + field: "score", + method: "max" + }, + { + field: "episodes", + method: "count" + }, + { + field: "rank", + method: "min" + }, + { + field: "members", + method: "sum" + } + ] + } +}); +~~~ + +## 示例 {#example} + +以下代码片段应用了自定义数学运算: + + + +**相关示例**: + +- [Pivot 2. 带别名的数据集](https://snippet.dhtmlx.com/7vc68rqd) +- [Pivot 2. 定义字段格式](https://snippet.dhtmlx.com/77nc4j8v) +- [Pivot 2. 外部筛选器](https://snippet.dhtmlx.com/s7tc9g4z) +- [Pivot 2. 列和行的总计](https://snippet.dhtmlx.com/f0ag0t9t) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/guides/working-with-server.md b/i18n/zh/docusaurus-plugin-content-docs/current/guides/working-with-server.md new file mode 100644 index 0000000..f04ce5a --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/guides/working-with-server.md @@ -0,0 +1,172 @@ +--- +sidebar_label: 与服务器配合使用 +title: 与服务器配合使用 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解如何将 Pivot 与后端集成。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载 DHTMLX Pivot 的免费 30 天评估版本。 +--- + +Pivot 完全在浏览器中运行。该 widget 接收一个原始行数组和一个 [`config`](/api/config/config-property)(rows / columns / values),并在客户端对行进行聚合。它没有内置的传输层,但公共 API 提供了与任何后端进行往返通信的钩子。 + +典型的集成包含三个部分: + +1. **加载**:初始化时从服务器加载原始的未聚合数据 +2. **保存配置**:当用户更改布局时保存 `config`,以便后续会话可以恢复 +3. **保存聚合表格**:当服务器需要汇总结果的快照时保存 + +## 从服务器加载原始数据 {#load-raw-data-from-the-server} + +[`data`](/api/config/data-property) 属性期望接收一个原始行对象数组。Pivot 自身完成行的聚合,因此服务器返回未汇总的数据。 + +使用 `fetch`(或任意 HTTP 客户端)拉取数据和字段,待响应到达后再构建 widget: + +~~~html +
+ + +~~~ + +如果服务器以 ISO 字符串形式返回日期字段,请在将数组传递给 Pivot 之前将其转换为 `Date` 实例。日期类型字段的聚合方法依赖真实的 `Date` 值: + +~~~jsx +data.forEach(row => { + if (typeof row.when === "string") row.when = new Date(row.when); +}); +~~~ + +:::info +**另请参阅**: +- [加载数据](/guides/loading-data) +- [日期格式化](/guides/localization#date-formatting) +::: + +## 保存用户布局以恢复会话 {#save-the-users-layout-to-resume-the-session} + +要让用户返回上次离开时的布局,需在每次更改时持久化 [`config`](/api/config/config-property) 对象。当用户通过 UI 编辑布局时,[`update-config`](/api/events/update-config-event) 事件会触发。其 payload 为经过处理的配置,结构为 `{ rows, columns, values, filters }`。 + +使用 [`api.on()`](/api/internal/on-method) 监听事件而不修改它。若处理函数需要更改事件 payload,则改用 [`api.intercept()`](/api/internal/intercept-method)。 + +以下示例订阅 `update-config` 事件,并将新布局 POST 到服务器: + +~~~html +
+ + +~~~ + +下次访问时,从 `/config` 返回已保存的配置,并在初始化时将其作为 `config` 属性传入。widget 将从上次的布局开始。如果布局在 widget 已存在后才到达,请使用 [`setConfig()`](/api/methods/setconfig-method) 方法应用已保存的配置。 + +当用户在配置面板中拖动字段时,频繁的更新可能会淹没服务器。可将 POST 包裹在定时器中以对调用进行防抖处理: + +~~~jsx +let saveTimer; +table.api.on("update-config", newConfig => { + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/config", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(newConfig), + }); + }, 300); +}); +~~~ + +:::note +`update-config` 的 payload 是*经过处理*的配置:Pivot 可能会将字段引用规范化为 `{ field, method }` 形式。初始化时将处理后的结构作为 `config` 属性传回即可,无需额外转换。 +::: + +:::tip +在处理函数中返回 `false` 可阻止布局更改。可利用此方式将持久化操作限制在服务器端验证通过后执行。 +::: + +## 保存聚合表格 {#save-the-aggregated-table} + +有时*结果本身*才是价值所在:渲染表格的服务器端缓存、定期报告或导出流水线。[`render-table`](/api/events/render-table-event) 事件在 Pivot 完成聚合后触发,携带完整的汇总表格:`columns`、`data` 行、`footer`、`split` 等。 + +以下示例订阅 `render-table` 事件并将快照 POST 到服务器,跳过首次渲染: + +~~~jsx +const table = new pivot.Pivot("#root", { data, fields, config }); + +let firstRender = true; +let saveTimer; + +table.api.on("render-table", ({ config: tableConfig }) => { + // 跳过首次聚合触发的初始渲染 + if (firstRender) { + firstRender = false; + return; + } + + clearTimeout(saveTimer); + saveTimer = setTimeout(() => { + fetch(server + "/snapshot", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + columns: tableConfig.columns, + data: tableConfig.data, + footer: tableConfig.footer, + split: tableConfig.split, + }), + }); + }, 300); +}); +~~~ + +:::note +`render-table` 事件比 `update-config` 触发更频繁。该事件在每次重新计算时运行,包括排序和展开/折叠操作。请对处理函数进行防抖处理并跳过首次渲染,以确保每次真实更改只发出一次 POST。 +::: + +:::tip +在处理函数中返回 `false` 可阻止渲染。可在服务器拒绝快照或用于只读模式时使用此方式。 +::: + +### 重新加载聚合快照 {#reload-an-aggregated-snapshot} + +Pivot 生成聚合表格,不显示预聚合的数据。[`data`](/api/config/data-property) 属性始终接收原始行。因此,从 `render-table` 保存的快照适用于以下场景: + +- 服务器端的下游导出流水线(CSV、XLSX) +- 使用已保存的 `columns` 和 `data` 通过普通数据表渲染的只读视图 +- 缓存的报告,可提供给其他用户而无需重新运行聚合 + +**相关文章**: + +- [加载数据](/guides/loading-data) +- [导出数据](/guides/exporting-data) + +**相关 API**: + +- [`api.on()`](/api/internal/on-method) +- [`update-config`](/api/events/update-config-event) +- [`render-table`](/api/events/render-table-event) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/how-to-start.md b/i18n/zh/docusaurus-plugin-content-docs/current/how-to-start.md new file mode 100644 index 0000000..09ec3ed --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/how-to-start.md @@ -0,0 +1,122 @@ +--- +sidebar_label: 快速入门 +title: 快速入门 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解如何开始使用 DHTMLX Pivot。浏览开发者指南和 API 参考,试用代码示例和在线演示,并下载免费 30 天评估版本的 DHTMLX Pivot。 +--- + +# 快速入门 {#how-to-start} + +本清晰全面的教程将引导您完成在页面上构建完整功能 Pivot 所需的步骤。 + +![pivot-main](/assets/pivot_main.png) + +## 步骤 1:下载并安装软件包 {#step-1-downloading-and-installing-packages} + +[下载软件包](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml)并将其解压到您的项目文件夹中。 + +您可以使用 `yarn` 或 `npm` 包管理器将 JavaScript Pivot 导入到您的项目中。 + +:::info +如果您想将 Pivot 集成到 React、Angular、Svelte 或 Vue 项目中,请参阅相应的[**集成指南**](/category/integration-with-frameworks/)以获取更多信息。 +::: + +### 通过 npm 或 yarn 安装试用版 Pivot {#installing-trial-pivot-via-npm-or-yarn} + +:::info +如果您想使用试用版 Pivot,请下载[**试用版 Pivot 软件包**](https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml)并按照 *README* 文件中的步骤操作。请注意,试用版 Pivot 仅可使用 30 天。 +::: + +### 通过 npm 或 yarn 安装 PRO 版 Pivot {#installing-pro-pivot-via-npm-or-yarn} + +:::info +您可以通过在[客户专区](https://dhtmlx.com/clients/)生成 **npm** 登录名和密码,直接访问 DHTMLX 私有 **npm**。详细的安装指南也可在该页面找到。请注意,访问私有 **npm** 仅在您的专有 Pivot 许可证有效期间可用。 +::: + +## 步骤 2:引入源文件 {#step-2-including-source-files} + +首先创建一个 HTML 文件,将其命名为 *index.html*,然后将 Pivot 源文件引入到该文件中。 + +需要引入两个必要文件: + +- Pivot 的 JS 文件 +- Pivot 的 CSS 文件 + +~~~html {5-6} title="index.html" + + + + How to Start with Pivot + + + + + + + +~~~ + +## 步骤 3:创建 Pivot {#step-3-creating-pivot} + +现在您可以将 Pivot 添加到页面中。首先,为 Pivot 创建一个 DIV 容器。 + +~~~html {} title="index.html" + + + + How to Start with Pivot + + + + +
+ + + +~~~ + +## 步骤 4:配置 Pivot {#step-4-configuring-pivot} + +接下来,您可以指定 Pivot 组件在初始化时所需的配置属性。 + +要开始使用 Pivot,首先需要提供初始数据。以下示例创建了一个包含以下内容的 Pivot: + +- *studio* 和 *genre* 的行 +- *title* 列 +- 使用 *max* 方法对 *score* 进行值聚合 + +**fields** 数组用于定义字段 ID、显示标签和数据类型。 + +**data** 数组应包含在 Pivot widget 中显示的实际数据,数组中的每个对象代表表格中的一行。 + +**config** 对象定义 Pivot 表格的结构,即哪些字段将作为表格的行和列,以及应对字段应用哪些数据聚合方法。 + +~~~jsx +const table = new pivot.Pivot("#root", { + //configuration properties + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +## 下一步 {#whats-next} + +就这些。只需这几个简单步骤,您便拥有了一个便捷的数据分析工具。现在您可以开始处理自己的任务,或继续深入探索 JavaScript Pivot 的世界: + +- [指南](/category/guides)页面提供有关安装、加载数据、样式设置及其他有用技巧的说明,帮助您顺畅地完成 Pivot 配置 +- [API 参考](api/overview/main-overview.md)提供 Pivot 功能的详细说明 diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/index.md b/i18n/zh/docusaurus-plugin-content-docs/current/index.md new file mode 100644 index 0000000..c4a53b6 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/index.md @@ -0,0 +1,103 @@ +--- +sidebar_label: Pivot 概述 +title: JavaScript Pivot 概述 +slug: / +description: 您可以在文档中了解 DHTMLX JavaScript Pivot 库的概述。浏览开发者指南和 API 参考,尝试代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费试用版本。 +--- + +# DHTMLX Pivot 概述 + +JavaScript Pivot 库是一个现成的组件,用于从大型数据集创建透视表。该 widget API 可以轻松适配您的 Web 应用程序需求。它为最终用户提供了在同一张表中比较和分析复杂数据的功能。 + +## Pivot 结构 {#pivot-structure} + +Pivot 界面由两个主要组件组成:配置面板和数据表格。 + +![Main](assets/pivot-main.png) + +## 配置面板 {#configuration-panel} + +配置面板允许向表格添加列和行,以及定义数据聚合方法的值字段。您可以通过面板中的以下区域添加各项内容: + +- 值:您可以添加定义数据聚合方式的值(例如求和、最小值、最大值) +- 列:您可以配置表格的列(定义哪些字段将作为列使用) +- 行:您可以配置哪些字段应作为表格的行使用 + +要隐藏配置面板,请点击**隐藏设置**按钮: + +![config_panel](assets/config_panel.png) + +### 值区域 {#values-area} + +在**值**区域,您可以定义将对透视表单元格应用哪些聚合方法(例如 min、max、count)。您可以执行以下操作: + +- 在值区域中添加和移除字段 +- 更改表格中值的顺序和优先级 +- 筛选数据 +- 设置将应用于表格字段的操作 + +有关更多详情,请参阅[区域操作](#operations-in-areas)和[筛选器](#filters)章节。 + +### 列区域 {#columns-area} + +在**列**区域,您可以执行以下操作: + +- 添加和移除列(即添加/移除作为列使用的字段) +- 更改表格中列的顺序和优先级 +- 筛选数据 + +有关更多详情,请参阅[区域操作](#operations-in-areas)和[筛选器](#filters)章节。 + +### 行区域 {#rows-area} + +在配置面板的**行**区域,您可以执行以下操作: + +- 添加和移除行(即添加/移除作为行使用的字段) +- 更改表格中行的顺序和优先级 +- 筛选数据 + +有关更多详情,请参阅[区域操作](#operations-in-areas)和[筛选器](#filters)章节。 + +### 区域操作 {#operations-in-areas} + +在配置面板的所有三个区域中,您都可以向表格添加或从表格中移除字段。如果您希望某个字段作为行或列使用,请在相应区域(列或行)中选择它。 + +要添加新字段,请在所需区域中点击"+"按钮,然后从下拉列表中选择名称。 + +要移除某项,请点击删除按钮("x")。 + +![add_remove](assets/add_remove.png) + +要更改表格中值/行/列的顺序,请将某项拖动到所需位置。在区域工具栏列表中,某项越靠左,其在表格中的优先级和位置越高。 + +![priority](assets/priority.png) + +要设置将应用于表格列所有数据的操作,请在**值**区域中,点击所需字段的值操作下拉列表,然后从列表中选择所需选项。 + +![operations](assets/operations.png) + +### 筛选器 {#filters} + +筛选器以下拉列表的形式出现在所有区域的每个字段中。Pivot 提供以下条件类型用于筛选: + +- 文本值:equal、notEqual、contains、notContains、beginsWith、notBeginsWith、endsWith、notEndsWith +- 数值:greater、less、greaterOrEqual、lessOrEqual、equal、notEqual、contains、notContains、begins with、not begins with、ends with、not ends with +- 日期类型:greater、less、greaterOrEqual、lessOrEqual、equal、notEqual、between、notBetween + +要筛选表格中的数据,请点击所需区域中某项的筛选标志,然后选择运算符并设置筛选值,最后点击**应用**。已应用筛选的字段将带有特殊的筛选标志。 + +![filters](assets/filter.png) + +## 表格 {#table} + +表格中的数据按照配置面板中的设置显示。点击列标题可启用列的**排序**功能: + +![table](assets/table.png) + +## 下一步 {#whats-next} + +现在您可以开始将 Pivot 集成到您的应用程序中。请参照[快速开始](how-to-start.md)教程的指引进行操作。 + +如果您使用 widget API 提供的功能,可以获得如下示例所示的具有更多特性的精美透视表: + + diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/news/migration.md b/i18n/zh/docusaurus-plugin-content-docs/current/news/migration.md new file mode 100644 index 0000000..5cdb0b5 --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/news/migration.md @@ -0,0 +1,57 @@ +--- +sidebar_label: 迁移至新版本 +title: 迁移至新版本 +description: 您可以在 DHTMLX JavaScript Pivot 库的文档中了解迁移至新版本的相关信息。浏览开发者指南和 API 参考,查看代码示例和在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 迁移至新版本 {#migration-to-newer-versions} + +## 2.0 -> 2.1 {#20---21} + +- `tableShape` 属性中 `sizes` 对象的 `colWidth` 参数已重命名为 `columnWidth` + +## 1.5 -> 2.0 {#15---20} + +以下变更列表将帮助您从 Pivot 1.5 的旧版本迁移至全面焕新的 Pivot 2.0 版本。 + +:::note +请查看我们的[数据迁移转换工具(从 v.1.5 迁移)](https://snippet.dhtmlx.com/s4sfdhq4) +::: + +### 变更的 API {#changed-api} + +#### 属性 {#properties} + +新属性并非完全复刻旧属性,而是提供了更为丰富的功能。 + +- [fieldList](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldlist_config.html) -> [fields](api/config/fields-property.md) +- [fields](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fields_config.html) -> [config](api/config/config-property.md) +- [mark](https://docs.dhtmlx.com/pivot/1-5/api__pivot_mark_config.html) -> [tableShape](api/config/tableshape-property.md) 属性的 `marks` 参数 +- [types](https://docs.dhtmlx.com/pivot/1-5/api__pivot_types_config.html) -> [methods](api/config/methods-property.md) +- [layout](https://docs.dhtmlx.com/pivot/1-5/api__pivot_layout_config.html) -> [columnShape](api/config/columnshape-property.md)、[headerShape](api/config/headershape-property.md)、[readonly](api/config/readonly-property.md) +- [customFormat](https://docs.dhtmlx.com/pivot/1-5/api__pivot_customformat_config.html) -> [predicates](api/config/predicates-property.md) - 用于数据的自定义预处理函数 + +#### Events {#events} + +- [filterApply](https://docs.dhtmlx.com/pivot/1-5/api__pivot_filterapply_event.html) -> [apply-filter](api/events/apply-filter-event.md) +- [fieldClick](https://docs.dhtmlx.com/pivot/1-5/api__pivot_fieldclick_event.html) -> 没有完全对应的 event,但您可以参考 [update-field](api/events/update-field-event.md) + +### 已移除的 API {#removed-api} + +- [1.5 版本的方法](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_methods.html) 已被废弃,所有新方法请参见:[方法](api/overview/main-overview.md#pivot-methods) +- [Pivot 1.5 事件](https://docs.dhtmlx.com/pivot/1-5/api__refs__pivot_events.html)(`change`、`fieldClick`、`applyButtonClick`)在 Pivot 2.0 中不再可用,但新版本提供了更丰富的功能(请参考 [Pivot 事件](api/overview/events-overview.md)) + +### 重要功能 {#important-features} + +- 数据导出:[旧版导出选项](https://docs.dhtmlx.com/pivot/1-5/guides__export.html) -> [新版导出选项](guides/exporting-data.md) +- 排序:[字段排序](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringfields) -> [数据排序](guides/working-with-data.md#sorting-data) +- 树形模式:[gridMode](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#gridmode) -> [启用树形模式](guides/configuration.md#enabling-the-tree-mode) +- 日期格式:[配置日期字段](https://docs.dhtmlx.com/pivot/1-5/guides__configuration.html#configuringdatefields) -> +[设置日期格式](guides/localization.md#date-formatting) +- 自定义: + - [单元格格式化](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#conditionalformattingofcells) -> [单元格样式](guides/stylization.md#cell-style) + - [表头模板](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforheaders) -> + [为表头应用模板](guides/configuration.md#applying-templates-to-headers) + - [单元格模板](https://docs.dhtmlx.com/pivot/1-5/guides__customization.html#settingtemplatesforcells) -> + [为单元格应用模板](guides/configuration.md#applying-templates-to-cells) +- 过滤:[操作过滤器](https://docs.dhtmlx.com/pivot/1-5/guides__using_filters.html) -> [数据过滤](guides/working-with-data.md#filtering-data) diff --git a/i18n/zh/docusaurus-plugin-content-docs/current/news/whats-new.md b/i18n/zh/docusaurus-plugin-content-docs/current/news/whats-new.md new file mode 100644 index 0000000..b608f2c --- /dev/null +++ b/i18n/zh/docusaurus-plugin-content-docs/current/news/whats-new.md @@ -0,0 +1,114 @@ +--- +sidebar_label: 最新动态 +title: 最新动态 +description: 您可以在 DHTMLX JavaScript UI 库的文档中查阅 DHTMLX Pivot 的最新功能和版本发布历史。浏览开发者指南和 API 参考,体验代码示例与在线演示,并下载 DHTMLX Pivot 的 30 天免费评估版本。 +--- + +# 最新动态 {#whats-new} + +如果您正从旧版本升级 Pivot,请查阅[迁移到新版本](news/migration.md)了解详情。 + +## 版本 2.1.1 {#version-211} + +发布于 2026 年 6 月 10 日 + +### 修复 {#fixes} + +- 当对包含缺失或空值的数据集应用行过滤器时,出现 "getMonth" 错误 + +## 版本 2.1 {#version-21} + +发布于 2025 年 5 月 6 日 + +### 新功能 {#new-functionality} + +- [支持从右侧冻结列](guides/configuration.md#freezing-columns-on-the-right) +- 数值的[默认对齐方式](guides/stylization.md#specific-css-classes)和[基于语言环境的格式化](guides/localization.md#number-formatting) +- 通过添加到 [`fields`](api/config/fields-property.md) 属性的 `format` 参数,[支持自定义数字格式](guides/working-with-data.md#applying-formats-to-fields)(适用于日期和数值字段) +- 通过 [`tableShape`](api/config/tableshape-property.md) 和 [`headerShape`](api/config/headershape-property.md) 属性的 `cellStyle` 参数,[支持设置表头和表格单元格的样式](guides/stylization.md#cell-style) +- 支持通过 [`pivot.template`](api/helpers/template.md) 辅助函数向表头和表格单元格插入 HTML 内容,方法是将模板定义为表头和列对象的 `cell` 属性(通过拦截 [render-table](api/events/render-table-event.md) 事件自定义表格) +- [Excel 和 CSV 导出设置增强](guides/exporting-data.md): + - 对于 "xlsx" 格式,日期和数字字段将以原始值导出,使用默认格式或通过 [`fields`](api/config/fields-property.md) 属性定义的格式 + - 支持定义文件名和工作表名称,并可从导出文件中排除表头/表尾 + - 支持为导出的单元格添加样式和模板 +- [支持通过外部输入过滤数据](api/table/filter-rows.md) +- 单元格导航的视觉边框 +- [与框架集成](/category/integration-with-frameworks) + +### 新增 API {#new-api} + +- [`tableShape`](api/config/tableshape-property.md) 中 `split` 对象的 `right` 设置 +- [`tableShape`](api/config/tableshape-property.md) 和 [`headerShape`](api/config/headershape-property.md) 属性中的 `cellStyle` 设置 +- [`fields`](api/config/fields-property.md) 数组中的 `format` 设置 +- 内部 Table 的 [`filter-rows`](api/table/filter-rows.md) 事件 +- 用于定义表格单元格 HTML 内容的 [`pivot.template`](api/helpers/template.md) + +### 修复 {#fixes-21} + +- 汇总列未按正确顺序排序 +- 导出时,以 0 开头的字符串值被转换为数字 +- 谓词模板未应用于行/列 +- 特定情况下出现 Resize observer 错误 + +### 破坏性变更 {#breaking-changes} + +- `tableShape` 属性中 `sizes` 对象的 `colWidth` 参数已重命名为 `columnWidth` + +## 版本 2.0.3 {#version-203} + +发布于 2024 年 11 月 29 日 + +### 修复 {#fixes-203} + +- 树形结构导出到 Excel/CSV 时仅包含最顶层分支 +- 自动宽度列导出后在 Excel 文件中显示过窄 +- 过滤器弹出窗口位置不正确 +- 使用 setConfig 方法更改配置后出现行为异常 +- 更精确的类型定义 + +## 版本 2.0.2 {#version-202} + +发布于 2024 年 10 月 22 日 + +### 修复 {#fixes-202} + +- `columnShape` 类型定义 +- 正确的包内容 + +## 版本 2.0 {#version-20} + +发布于 2024 年 8 月 26 日 + +请查阅[博客页面](https://dhtmlx.com/blog/)了解本次版本发布的详细介绍。 + +### 破坏性变更 {#breaking-change} + +:::note +版本 1.5 的 API 与 API v.2.0 不兼容。 +::: + +有关迁移到新版本的建议,请查阅[迁移](news/migration.md)页面。 + +### 新功能 {#new-functionality-20} + +- Pivot 2.0 在渲染和生成大型数据集方面速度更快([示例](https://snippet.dhtmlx.com/e6qwqrys)) +- 通过 [`columnShape`](api/config/columnshape-property.md) 属性可使用以下新的列外观和行为配置功能: + - 设置 **autowidth**,并可指定用于计算 **autoWidth** 的最大处理行数([示例](https://snippet.dhtmlx.com/tn1yw14m)) + - **firstOnly** 功能:在计算列宽时,每个相同数据字段仅分析一次(默认行为) +- 现在可以通过 [`headerShape`](api/config/headershape-property.md) 属性配置表头的外观和行为,包括: + - 为表头文本应用模板([示例](https://snippet.dhtmlx.com/g89r9ryw)) + - 更改文本方向([示例](https://snippet.dhtmlx.com/4qroi8ka)) + - 使列可折叠([示例](https://snippet.dhtmlx.com/pt2ljmcm)) +- 可通过 [`tableShape`](api/config/tableshape-property.md) 属性配置表格的外观和尺寸,支持: + - 配置行、表头、表尾的高度:rowHeight、headerHeight、footerHeight([调整表格尺寸](guides/configuration.md#resizing-the-table)) + - 不仅为列生成汇总值,也可为行生成汇总值,这通过 `tableShape` 属性的 **totalColumn** 参数实现([示例](https://snippet.dhtmlx.com/f0ag0t9t)) + - 在表格视图中隐藏重复值([`tableShape`](api/config/tableshape-property.md) 属性的 **cleanRows** 参数) + - 从左侧固定列,使其在滚动时保持静止([示例](https://snippet.dhtmlx.com/lahf729o)) + - 展开或折叠所有行([示例](https://snippet.dhtmlx.com/i4mi6ejn)) +- 数据聚合新增更多功能: + - [限制加载的数据量](guides/working-with-data.md#limiting-loaded-data) + - 支持更多[数据操作](guides/working-with-data.md#applying-maths-methods) + - [使用谓词处理数据](guides/working-with-data.md#processing-data-with-predicates) — 为数据应用自定义预处理函数 + - [通过语言环境设置日期格式](guides/localization.md#date-formatting) +- 新增方法:[`getTable()`](api/methods/gettable-method.md)、[`setConfig()`](api/methods/setconfig-method.md)、[`setLocale()`](api/methods/setlocale-method.md)、[`showConfigPanel()`](api/methods/showconfigpanel-method.md) +- 新增事件:[`add-field`](api/events/add-field-event.md)、[`delete-field`](api/events/delete-field-event.md)、[`open-filter`](api/events/open-filter-event.md)、[`render-table`](api/events/render-table-event.md)、[`move-field`](api/events/move-field-event.md)、[`show-config-panel`](api/events/show-config-panel-event.md)、[`show-config-panel`](api/events/show-config-panel-event.md)、[`update-config`](api/events/update-config-event.md)、[`update-field`](api/events/update-field-event.md)。 diff --git a/i18n/zh/docusaurus-theme-classic/footer.json b/i18n/zh/docusaurus-theme-classic/footer.json new file mode 100644 index 0000000..bc2018e --- /dev/null +++ b/i18n/zh/docusaurus-theme-classic/footer.json @@ -0,0 +1,62 @@ +{ + "link.title.Development center": { + "message": "开发中心", + "description": "The title of the footer links column with title=Development center in the footer" + }, + "link.title.Community": { + "message": "社区", + "description": "The title of the footer links column with title=Community in the footer" + }, + "link.title.Company": { + "message": "公司", + "description": "The title of the footer links column with title=Company in the footer" + }, + "link.item.label.Download JS Pivot": { + "message": "下载 JS Pivot", + "description": "The label of footer link with label=Download JS Pivot linking to https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml" + }, + "link.item.label.Examples": { + "message": "示例", + "description": "The label of footer link with label=Examples linking to https://snippet.dhtmlx.com/mhymus00?tag=pivot" + }, + "link.item.label.Blog": { + "message": "博客", + "description": "The label of footer link with label=Blog linking to https://dhtmlx.com/blog/tag/pivot/" + }, + "link.item.label.Forum": { + "message": "论坛", + "description": "The label of footer link with label=Forum linking to https://forum.dhtmlx.com/c/pivot/16" + }, + "link.item.label.GitHub": { + "message": "GitHub", + "description": "The label of footer link with label=GitHub linking to https://github.com/DHTMLX" + }, + "link.item.label.Youtube": { + "message": "Youtube", + "description": "The label of footer link with label=Youtube linking to https://www.youtube.com/user/dhtmlx" + }, + "link.item.label.Facebook": { + "message": "Facebook", + "description": "The label of footer link with label=Facebook linking to https://www.facebook.com/dhtmlx" + }, + "link.item.label.Twitter": { + "message": "Twitter", + "description": "The label of footer link with label=Twitter linking to https://twitter.com/dhtmlx" + }, + "link.item.label.Linkedin": { + "message": "领英", + "description": "The label of footer link with label=Linkedin linking to https://www.linkedin.com/groups/3345009/" + }, + "link.item.label.About us": { + "message": "关于我们", + "description": "The label of footer link with label=About us linking to https://dhtmlx.com/docs/company.shtml" + }, + "link.item.label.Contact us": { + "message": "联系我们", + "description": "The label of footer link with label=Contact us linking to https://dhtmlx.com/docs/contact.shtml" + }, + "link.item.label.Licensing": { + "message": "许可协议", + "description": "The label of footer link with label=Licensing linking to https://dhtmlx.com/docs/products/dhtmlxPivot/#licensing" + } +} diff --git a/i18n/zh/docusaurus-theme-classic/navbar.json b/i18n/zh/docusaurus-theme-classic/navbar.json new file mode 100644 index 0000000..bc98a25 --- /dev/null +++ b/i18n/zh/docusaurus-theme-classic/navbar.json @@ -0,0 +1,26 @@ +{ + "title": { + "message": "JavaScript Pivot 文档", + "description": "The title in the navbar" + }, + "logo.alt": { + "message": "DHTMLX JavaScript Pivot 标志", + "description": "The alt text of navbar logo" + }, + "item.label.Examples": { + "message": "示例", + "description": "Navbar item with label Examples" + }, + "item.label.Forum": { + "message": "论坛", + "description": "Navbar item with label Forum" + }, + "item.label.Support": { + "message": "支持", + "description": "Navbar item with label Support" + }, + "item.label.Download": { + "message": "下载", + "description": "Navbar item with label Download" + } +} diff --git a/plugins/dhx-md-data-transformer-plugin.js b/plugins/dhx-md-data-transformer-plugin.js index 789ab3b..31188d5 100644 --- a/plugins/dhx-md-data-transformer-plugin.js +++ b/plugins/dhx-md-data-transformer-plugin.js @@ -17,7 +17,7 @@ module.exports = (context, options) => { module: { rules: [ { - include: [path.resolve(siteDir, 'docs')], + include: [path.resolve(siteDir, 'docs'), path.resolve(siteDir, 'i18n')], test: /(\.mdx?)$/, use: [ { diff --git a/sidebars.js b/sidebars.js index 273cbeb..c87a111 100644 --- a/sidebars.js +++ b/sidebars.js @@ -119,7 +119,7 @@ module.exports = { "api/events/render-table-event", "api/events/show-config-panel-event", "api/events/update-config-event", - "api/events/update-value-event" + "api/events/update-field-event" ] }, { @@ -220,6 +220,7 @@ module.exports = { "guides/stylization", "guides/typescript-support", "guides/working-with-data", + "guides/working-with-server", ] }