diff --git a/docs/api/config/columnshape-property.md b/docs/api/config/columnshape-property.md index ea6134a..ce45d68 100644 --- a/docs/api/config/columnshape-property.md +++ b/docs/api/config/columnshape-property.md @@ -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/configpanel-property.md b/docs/api/config/configpanel-property.md index 4d0c92c..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:** +**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 fc5cb21..996d257 100644 --- a/docs/api/config/fields-property.md +++ b/docs/api/config/fields-property.md @@ -109,4 +109,4 @@ const table = new pivot.Pivot("#root", { - [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/limits-property.md b/docs/api/config/limits-property.md index 4b6c54e..819b2d3 100644 --- a/docs/api/config/limits-property.md +++ b/docs/api/config/limits-property.md @@ -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/methods-property.md b/docs/api/config/methods-property.md index d3702f7..4541b0c 100644 --- a/docs/api/config/methods-property.md +++ b/docs/api/config/methods-property.md @@ -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.md#applying-maths-methods) 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 fe1b8b0..afa57d1 100644 --- a/docs/api/config/tableshape-property.md +++ b/docs/api/config/tableshape-property.md @@ -118,7 +118,7 @@ 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) diff --git a/docs/api/events/render-table-event.md b/docs/api/events/render-table-event.md index 324321e..2233ea2 100644 --- a/docs/api/events/render-table-event.md +++ b/docs/api/events/render-table-event.md @@ -173,6 +173,6 @@ function closeAll() { 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.md) +**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/helpers/template.md b/docs/api/helpers/template.md index 1172023..be2dc08 100644 --- a/docs/api/helpers/template.md +++ b/docs/api/helpers/template.md @@ -82,7 +82,7 @@ The snippet demonstrates how you can add icons to: -**Related articles:** +**Related articles**: - [`render-table`](api/events/render-table-event.md) - [Applying templates to cells](guides/configuration.md#applying-templates-to-cells) diff --git a/docs/api/methods/gettable-method.md b/docs/api/methods/gettable-method.md index 803d2a8..a2c96f4 100644 --- a/docs/api/methods/gettable-method.md +++ b/docs/api/methods/gettable-method.md @@ -67,7 +67,7 @@ exportButton.textContent = "Export"; document.body.appendChild(exportButton); ~~~ -**Related articles:**: +**Related articles**: - [`close-row`](api/table/close-row.md) - [`export`](api/table/export.md) diff --git a/docs/api/table/export.md b/docs/api/table/export.md index a99f976..0653a71 100644 --- a/docs/api/table/export.md +++ b/docs/api/table/export.md @@ -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: @@ -92,7 +92,7 @@ The `export` action of the Table widget has the next parameters that you can con 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 diff --git a/docs/guides/configuration.md b/docs/guides/configuration.md index 01cb9aa..1f6437e 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -732,7 +732,7 @@ The Configuration panel supports the following field operations: - [`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) diff --git a/docs/guides/loading-data.md b/docs/guides/loading-data.md index 48aa226..86f08e8 100644 --- a/docs/guides/loading-data.md +++ b/docs/guides/loading-data.md @@ -159,15 +159,9 @@ Promise.all([ }); ~~~ -<<<<<<< sp-next-add-backend-guide -:::info -See [Working with server](/guides/working-with-server) for a full round-trip: loading rows, saving the layout, and storing aggregated results. -::: +Refer to the following topic for additional information: [Working with server](/guides/working-with-server) -## Loading CSV data -======= ## Load CSV data ->>>>>>> next 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. @@ -277,7 +271,7 @@ 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) diff --git a/docs/guides/working-with-data.md b/docs/guides/working-with-data.md index fea77dc..ab26158 100644 --- a/docs/guides/working-with-data.md +++ b/docs/guides/working-with-data.md @@ -679,7 +679,7 @@ The snippet below applies custom math operations: -**Related samples:** +**Related samples**: - [Pivot 2. Dataset with aliases](https://snippet.dhtmlx.com/7vc68rqd) - [Pivot 2. Defining fields formats](https://snippet.dhtmlx.com/77nc4j8v) diff --git a/docs/guides/working-with-server.md b/docs/guides/working-with-server.md index 5db7c19..79e9c80 100644 --- a/docs/guides/working-with-server.md +++ b/docs/guides/working-with-server.md @@ -8,9 +8,9 @@ Pivot runs entirely in the browser. The widget takes an array of raw rows plus a A typical integration includes three parts: -1. **Load** raw, non-aggregated data from the server on init. -2. **Save the config** when the user changes the layout, so the session resumes later. -3. **Save the aggregated table** when the server needs a snapshot of the rolled-up result. +1. **Load** raw, non-aggregated data from the server on init +2. **Save the config** when the user changes the layout, so the session resumes later +3. **Save the aggregated table** when the server needs a snapshot of the rolled-up result ## Load raw data from the server @@ -47,7 +47,9 @@ data.forEach(row => { ~~~ :::info -See also: [Loading data](/guides/loading-data), [Date formatting](/guides/localization#date-formatting). +**See also**: +- [Loading data](/guides/loading-data) +- [Date formatting](/guides/localization#date-formatting) ::: ## Save the user's layout to resume the session @@ -154,16 +156,17 @@ Return `false` from the handler to prevent rendering. Use this when the server r Pivot produces aggregated tables and does not display pre-aggregated ones. The [`data`](/api/config/data-property) property always takes raw rows. A snapshot saved from `render-table` therefore fits these cases: -- a downstream export pipeline (CSV, XLSX) on the server, -- a read-only view rendered by a plain data table from the saved `columns` and `data`, -- a cached report served to other users without re-running the aggregation. - ---- +- a downstream export pipeline (CSV, XLSX) on the server +- a read-only view rendered by a plain data table from the saved `columns` and `data` +- a cached report served to other users without re-running the aggregation **Related articles**: - [Loading data](/guides/loading-data) - [Exporting data](/guides/exporting-data) + +**Related API**: + - [`api.on()`](/api/internal/on-method) -- [`update-config` event](/api/events/update-config-event) -- [`render-table` event](/api/events/render-table-event) +- [`update-config`](/api/events/update-config-event) +- [`render-table`](/api/events/render-table-event) diff --git a/docusaurus.config.js b/docusaurus.config.js index f32e8ce..ca262ee 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -141,6 +141,17 @@ const onAfterDataTransformation = (data) => { /** @type {import('@docusaurus/types').Config} */ const config = { + i18n: { + defaultLocale: 'en', + locales: ['en', 'de', 'ru', 'zh', 'ko'], + localeConfigs: { + en: { label: 'English', htmlLang: 'en-US' }, + de: { label: 'Deutsch', htmlLang: 'de' }, + ru: { label: 'Русский', htmlLang: 'ru' }, + zh: { label: '简体中文', htmlLang: 'zh-CN' }, + ko: { label: '한국어', htmlLang: 'ko' }, + }, + }, noIndex: false, title: 'DHTMLX JavaScript Pivot Docs', tagline: 'DHTMLX JavaScript Pivot Docs', @@ -164,7 +175,7 @@ const config = { ({ docs: { sidebarPath: require.resolve('./sidebars.js'), - editUrl: 'https://github.com/DHTMLX/docs-pivot/edit/master/', + // editUrl: 'https://github.com/DHTMLX/docs-pivot/edit/master/', routeBasePath: '/', }, theme: { @@ -207,7 +218,8 @@ const config = { highlightSearchTermsOnTargetPage: true, removeDefaultStemmer: true, removeDefaultStopWordFilter: true, - explicitSearchResultPath: true + explicitSearchResultPath: true, + language: ["en", "de", "ru", "zh"] } ] ], @@ -250,7 +262,11 @@ const config = { "label": "Download", "href": "https://dhtmlx.com/docs/products/dhtmlxPivot/download.shtml", "position": "right" - } + }, + { + type: 'localeDropdown', + position: 'right', + }, ], }, footer: { diff --git a/i18n/de/code.json b/i18n/de/code.json new file mode 100644 index 0000000..064116f --- /dev/null +++ b/i18n/de/code.json @@ -0,0 +1,364 @@ +{ + "theme.ErrorPageContent.title": { + "message": "Diese Seite ist abgestürzt.", + "description": "The title of the fallback page when the page crashed" + }, + "theme.BackToTopButton.buttonAriaLabel": { + "message": "Zurück nach oben scrollen", + "description": "The ARIA label for the back to top button" + }, + "theme.blog.archive.title": { + "message": "Archiv", + "description": "The page & hero title of the blog archive page" + }, + "theme.blog.archive.description": { + "message": "Archiv", + "description": "The page & hero description of the blog archive page" + }, + "theme.blog.paginator.navAriaLabel": { + "message": "Navigation der Blog-Listen-Seite", + "description": "The ARIA label for the blog pagination" + }, + "theme.blog.paginator.newerEntries": { + "message": "Neuere Einträge", + "description": "The label used to navigate to the newer blog posts page (previous page)" + }, + "theme.blog.paginator.olderEntries": { + "message": "Ältere Einträge", + "description": "The label used to navigate to the older blog posts page (next page)" + }, + "theme.blog.post.paginator.navAriaLabel": { + "message": "Navigation der Blog-Post-Seite", + "description": "The ARIA label for the blog posts pagination" + }, + "theme.blog.post.paginator.newerPost": { + "message": "Neuerer Beitrag", + "description": "The blog post button label to navigate to the newer/previous post" + }, + "theme.blog.post.paginator.olderPost": { + "message": "Älterer Beitrag", + "description": "The blog post button label to navigate to the older/next post" + }, + "theme.tags.tagsPageLink": { + "message": "Alle Tags anzeigen", + "description": "The label of the link targeting the tag list page" + }, + "theme.colorToggle.ariaLabel.mode.system": { + "message": "Systemmodus", + "description": "The name for the system color mode" + }, + "theme.colorToggle.ariaLabel.mode.light": { + "message": "Hellmodus", + "description": "The name for the light color mode" + }, + "theme.colorToggle.ariaLabel.mode.dark": { + "message": "Dunkelmodus", + "description": "The name for the dark color mode" + }, + "theme.colorToggle.ariaLabel": { + "message": "Wechsel zwischen Dunkel- und Hellmodus (aktuell {mode})", + "description": "The ARIA label for the color mode toggle" + }, + "theme.docs.breadcrumbs.navAriaLabel": { + "message": "Brotkrumen", + "description": "The ARIA label for the breadcrumbs" + }, + "theme.docs.DocCard.categoryDescription.plurals": { + "message": "1 Element|{count} Elemente", + "description": "The default description for a category card in the generated index about how many items this category includes" + }, + "theme.docs.paginator.navAriaLabel": { + "message": "Dokumentationsseiten", + "description": "The ARIA label for the docs pagination" + }, + "theme.docs.paginator.previous": { + "message": "Zurück", + "description": "The label used to navigate to the previous doc" + }, + "theme.docs.paginator.next": { + "message": "Weiter", + "description": "The label used to navigate to the next doc" + }, + "theme.docs.tagDocListPageTitle.nDocsTagged": { + "message": "Ein Dokument markiert|{count} Dokumente markiert", + "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} mit \"{tagName}\"", + "description": "The title of the page for a docs tag" + }, + "theme.docs.versionBadge.label": { + "message": "Version: {versionLabel}" + }, + "theme.docs.versions.unreleasedVersionLabel": { + "message": "Dies ist unreleased Dokumentation für {siteTitle} Version {versionLabel}.", + "description": "The label used to tell the user that he's browsing an unreleased doc version" + }, + "theme.docs.versions.unmaintainedVersionLabel": { + "message": "Dies ist die Dokumentation für {siteTitle} Version {versionLabel}, die nicht mehr aktiv gepflegt wird.", + "description": "The label used to tell the user that he's browsing an unmaintained doc version" + }, + "theme.docs.versions.latestVersionSuggestionLabel": { + "message": "Für aktuelle Dokumentation siehe {latestVersionLink} ({versionLabel}).", + "description": "The label used to tell the user to check the latest version" + }, + "theme.docs.versions.latestVersionLinkLabel": { + "message": "neueste Version", + "description": "The label used for the latest version suggestion link label" + }, + "theme.common.editThisPage": { + "message": "Diese Seite bearbeiten", + "description": "The link label to edit the current page" + }, + "theme.common.headingLinkTitle": { + "message": "Direktlink zu {heading}", + "description": "Title for link to heading" + }, + "theme.lastUpdated.atDate": { + "message": " am {date}", + "description": "The words used to describe on which date a page has been last updated" + }, + "theme.lastUpdated.byUser": { + "message": " von {user}", + "description": "The words used to describe by who the page has been last updated" + }, + "theme.lastUpdated.lastUpdatedAtBy": { + "message": "Zuletzt aktualisiert{atDate}{byUser}", + "description": "The sentence used to display when a page has been last updated, and by who" + }, + "theme.NotFound.title": { + "message": "Seite nicht gefunden", + "description": "The title of the 404 page" + }, + "theme.navbar.mobileVersionsDropdown.label": { + "message": "Versionen", + "description": "The label for the navbar versions dropdown on mobile view" + }, + "theme.tags.tagsListLabel": { + "message": "Tags:", + "description": "The label alongside a tag list" + }, + "theme.admonition.caution": { + "message": "Vorsicht", + "description": "The default label used for the Caution admonition (:::caution)" + }, + "theme.admonition.danger": { + "message": "Gefahr", + "description": "The default label used for the Danger admonition (:::danger)" + }, + "theme.admonition.info": { + "message": "Info", + "description": "The default label used for the Info admonition (:::info)" + }, + "theme.admonition.note": { + "message": "Hinweis", + "description": "The default label used for the Note admonition (:::note)" + }, + "theme.admonition.tip": { + "message": "Tipp", + "description": "The default label used for the Tip admonition (:::tip)" + }, + "theme.admonition.warning": { + "message": "Warnung", + "description": "The default label used for the Warning admonition (:::warning)" + }, + "theme.AnnouncementBar.closeButtonAriaLabel": { + "message": "Schließen", + "description": "The ARIA label for close button of announcement bar" + }, + "theme.blog.sidebar.navAriaLabel": { + "message": "Navigation der neuesten Blogbeiträge", + "description": "The ARIA label for recent posts in the blog sidebar" + }, + "theme.DocSidebarItem.expandCategoryAriaLabel": { + "message": "Seitenleisten-Kategorie '{label}' erweitern", + "description": "The ARIA label to expand the sidebar category" + }, + "theme.DocSidebarItem.collapseCategoryAriaLabel": { + "message": "Seitenleisten-Kategorie '{label}' reduzieren", + "description": "The ARIA label to collapse the sidebar category" + }, + "theme.IconExternalLink.ariaLabel": { + "message": "(öffnet in neuem Tab)", + "description": "The ARIA label for the external link icon" + }, + "theme.NavBar.navAriaLabel": { + "message": "Hauptnavigation", + "description": "The ARIA label for the main navigation" + }, + "theme.NotFound.p1": { + "message": "Wir konnten nicht finden, wonach Sie gesucht haben.", + "description": "The first paragraph of the 404 page" + }, + "theme.NotFound.p2": { + "message": "Bitte kontaktieren Sie den Besitzer der Website, der Sie zum ursprünglichen URL verlinkt hat, und informieren Sie ihn, dass der Link defekt ist.", + "description": "The 2nd paragraph of the 404 page" + }, + "theme.navbar.mobileLanguageDropdown.label": { + "message": "Sprachen", + "description": "The label for the mobile language switcher dropdown" + }, + "theme.TOCCollapsible.toggleButtonLabel": { + "message": "Auf dieser Seite", + "description": "The label used by the button on the collapsible TOC component" + }, + "theme.blog.post.readMore": { + "message": "Weiterlesen", + "description": "The label used in blog post item excerpts to link to full blog posts" + }, + "theme.blog.post.readMoreLabel": { + "message": "Mehr lesen über {title}", + "description": "The ARIA label for the link to full blog posts from excerpts" + }, + "theme.blog.post.readingTime.plurals": { + "message": "Eine Minute lesen|{readingTime} Minuten lesen", + "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": "Kopieren", + "description": "The copy button label on code blocks" + }, + "theme.CodeBlock.copied": { + "message": "Kopiert", + "description": "The copied button label on code blocks" + }, + "theme.CodeBlock.copyButtonAriaLabel": { + "message": "Code in die Zwischenablage kopieren", + "description": "The ARIA label for copy code blocks button" + }, + "theme.CodeBlock.wordWrapToggle": { + "message": "Zeilenumbruch umschalten", + "description": "The title attribute for toggle word wrapping button of code block lines" + }, + "theme.docs.breadcrumbs.home": { + "message": "Startseite", + "description": "The ARIA label for the home page in the breadcrumbs" + }, + "theme.docs.sidebar.collapseButtonTitle": { + "message": "Seitenleiste einklappen", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.collapseButtonAriaLabel": { + "message": "Seitenleiste einklappen", + "description": "The title attribute for collapse button of doc sidebar" + }, + "theme.docs.sidebar.navAriaLabel": { + "message": "Dokumentations-Seitenleiste", + "description": "The ARIA label for the sidebar navigation" + }, + "theme.docs.sidebar.closeSidebarButtonAriaLabel": { + "message": "Navigationsleiste schließen", + "description": "The ARIA label for close button of mobile sidebar" + }, + "theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": { + "message": "← Zurück zum Hauptmenü", + "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": "Navigationsleiste umschalten", + "description": "The ARIA label for hamburger menu button of mobile navigation" + }, + "theme.navbar.mobileDropdown.collapseButton.expandAriaLabel": { + "message": "Dropdown ausklappen", + "description": "The ARIA label of the button to expand the mobile dropdown navbar item" + }, + "theme.navbar.mobileDropdown.collapseButton.collapseAriaLabel": { + "message": "Dropdown einklappen", + "description": "The ARIA label of the button to collapse the mobile dropdown navbar item" + }, + "theme.docs.sidebar.expandButtonTitle": { + "message": "Seitenleiste erweitern", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.docs.sidebar.expandButtonAriaLabel": { + "message": "Seitenleiste erweitern", + "description": "The ARIA label and title attribute for expand button of doc sidebar" + }, + "theme.SearchBar.noResultsText": { + "message": "Keine Ergebnisse" + }, + "theme.SearchBar.seeAllOutsideContext": { + "message": "Alle Ergebnisse außerhalb von \"{context}\" anzeigen" + }, + "theme.SearchBar.searchInContext": { + "message": "Alle Ergebnisse innerhalb von \"{context}\" anzeigen" + }, + "theme.SearchBar.seeAll": { + "message": "Alle {count} Ergebnisse anzeigen" + }, + "theme.SearchBar.label": { + "message": "Suche", + "description": "The ARIA label and placeholder for search button" + }, + "theme.SearchPage.existingResultsTitle": { + "message": "Suchergebnisse für „{query}“", + "description": "The search page title for non-empty query" + }, + "theme.SearchPage.emptyResultsTitle": { + "message": "Dokumentation durchsuchen", + "description": "The search page title for empty query" + }, + "theme.SearchPage.searchContext.everywhere": { + "message": "Überall" + }, + "theme.SearchPage.documentsFound.plurals": { + "message": "Ein Dokument gefunden|{count} Dokumente gefunden", + "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": "Keine Ergebnisse gefunden", + "description": "The paragraph for empty search result" + }, + "theme.blog.post.plurals": { + "message": "Ein Beitrag|{count} Beiträge", + "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} markiert mit „{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": "Autoren", + "description": "The title of the authors page" + }, + "theme.blog.authorsList.viewAll": { + "message": "Alle Autoren anzeigen", + "description": "The label of the link targeting the blog authors page" + }, + "theme.blog.author.noPosts": { + "message": "Dieser Autor hat noch keine Beiträge geschrieben.", + "description": "The text for authors with 0 blog post" + }, + "theme.contentVisibility.unlistedBanner.title": { + "message": "Nicht gelistete Seite", + "description": "The unlisted content banner title" + }, + "theme.contentVisibility.unlistedBanner.message": { + "message": "Diese Seite ist nicht gelistet. Suchmaschinen werden sie nicht indexieren, und nur Benutzer mit direktem Link können darauf zugreifen.", + "description": "The unlisted content banner message" + }, + "theme.contentVisibility.draftBanner.title": { + "message": "Entwurfsseite", + "description": "The draft content banner title" + }, + "theme.contentVisibility.draftBanner.message": { + "message": "Diese Seite ist ein Entwurf. Sie ist nur in der Entwicklungsumgebung sichtbar und wird im Produktions-Build ausgeschlossen.", + "description": "The draft content banner message" + }, + "theme.ErrorPageContent.tryAgain": { + "message": "Erneut versuchen", + "description": "The label of the button to try again rendering when the React error boundary captures an error" + }, + "theme.common.skipToMainContent": { + "message": "Zum Hauptinhalt springen", + "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": "Tags", + "description": "The title of the tag list page" + } +} diff --git a/i18n/de/docusaurus-plugin-content-blog/options.json b/i18n/de/docusaurus-plugin-content-blog/options.json new file mode 100644 index 0000000..0199e5c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-blog/options.json @@ -0,0 +1,14 @@ +{ + "title": { + "message": "Blog", + "description": "The title for the blog used in SEO" + }, + "description": { + "message": "Blog", + "description": "The description for the blog used in SEO" + }, + "sidebar.title": { + "message": "Neueste Beiträge", + "description": "The label for the left sidebar" + } +} diff --git a/i18n/de/docusaurus-plugin-content-docs/current.json b/i18n/de/docusaurus-plugin-content-docs/current.json new file mode 100644 index 0000000..43acc5c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current.json @@ -0,0 +1,70 @@ +{ + "version.label": { + "message": "Nächste", + "description": "The label for version current" + }, + "sidebar.docs.category.What's new and migration": { + "message": "Neuigkeiten und Migration", + "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": "Neuigkeiten und Migration", + "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-Methoden", + "description": "The label for category 'Pivot methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API": { + "message": "Pivot interne API", + "description": "The label for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot internal API.link.generated-index.title": { + "message": "Übersicht interne API", + "description": "The generated-index page title for category 'Pivot internal API' in sidebar 'docs'" + }, + "sidebar.docs.category.Event Bus methods": { + "message": "Event-Bus-Methoden", + "description": "The label for category 'Event Bus methods' in sidebar 'docs'" + }, + "sidebar.docs.category.State methods": { + "message": "Status-Methoden", + "description": "The label for category 'State methods' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot events": { + "message": "Pivot-Ereignisse", + "description": "The label for category 'Pivot events' in sidebar 'docs'" + }, + "sidebar.docs.category.Pivot properties": { + "message": "Pivot-Eigenschaften", + "description": "The label for category 'Pivot properties' in sidebar 'docs'" + }, + "sidebar.docs.category.Table events": { + "message": "Table-Ereignisse", + "description": "The label for category 'Table events' in sidebar 'docs'" + }, + "sidebar.docs.category.Helpers": { + "message": "Helfer", + "description": "The label for category 'Helpers' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks": { + "message": "Integration mit Frameworks", + "description": "The label for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Integration with frameworks.link.generated-index.title": { + "message": "Integration mit Frameworks", + "description": "The generated-index page title for category 'Integration with frameworks' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides": { + "message": "Anleitungen", + "description": "The label for category 'Guides' in sidebar 'docs'" + }, + "sidebar.docs.category.Guides.link.generated-index.title": { + "message": "Anleitungen", + "description": "The generated-index page title for category 'Guides' in sidebar 'docs'" + } +} diff --git a/i18n/de/docusaurus-plugin-content-docs/current/.sync b/i18n/de/docusaurus-plugin-content-docs/current/.sync new file mode 100644 index 0000000..3903d9d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/.sync @@ -0,0 +1 @@ +995cefe31a5c2b36bb2762d2d75586bfe042285b diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md new file mode 100644 index 0000000..9727b2d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/columnshape-property.md @@ -0,0 +1,82 @@ +--- +sidebar_label: columnShape +title: columnShape Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die columnShape-Konfiguration. Durchsuchen Sie Entwickleranleitungen und API-Referenzen, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# columnShape + +### Beschreibung {#description} + +@short: Optional. Konfiguriert das Aussehen und Verhalten der Pivot-Spalten + +### Verwendung {#usage} + +~~~jsx +columnShape?: { + sort?: boolean, + width?: { + [field: string]: number + }, + autoWidth?: { + columns: { + [field: string]: boolean + }, + auto?: boolean | "header" | "data", + maxRows?: number, + firstOnly?: boolean + } +}; +~~~ + +### Parameter {#parameters} + +- `sort` - (optional) wenn **true** (Standard), ist die Sortierung in der Benutzeroberfläche durch Klicken auf den Spaltenheader aktiviert; wenn **false**, ist die Sortierung deaktiviert +- `width` - (optional) definiert die Breite einer Spalte; es handelt sich um ein Objekt, bei dem jeder Schlüssel eine Feld-ID ist und der Wert die Breite der Spalte in Pixeln angibt +- `autoWidth` - (optional) ein Objekt, das festlegt, wie die Spaltenbreite automatisch berechnet werden soll. Die Standardkonfiguration verwendet 20 Zeilen, und die Breite wird anhand von Header und Daten berechnet, wobei jedes Feld nur einmal analysiert wird. Die Objektparameter sind folgende: + - `columns` - (erforderlich) ein Objekt, bei dem jeder Schlüssel eine Feld-ID ist und der boolesche Wert angibt, ob die Spaltenbreite automatisch berechnet werden soll + - `auto` - (optional) wenn auf **header** gesetzt, wird die Breite an den Header-Text angepasst; wenn auf **data** gesetzt, wird die Breite an die Zelle mit dem breitesten Inhalt angepasst; wenn auf **true** gesetzt, wird die Breite an den Inhalt von Headern und Zellen angepasst. + Wenn autowidth auf **false** gesetzt ist, wird der `width`-Wert verwendet oder der Wert von `columnWidth` aus der [`tableShape`](api/config/tableshape-property.md)-Eigenschaft angewendet. + - `maxRows` - (optional) die Anzahl der Zeilen, die für die autoWidth-Berechnung verarbeitet werden sollen + - `firstOnly` - (optional) wenn auf **true** gesetzt (Standard), wird jedes Feld derselben Daten nur einmal analysiert, um die Spaltenbreite zu berechnen; bei mehreren Spalten, die auf denselben Daten basieren (z. B. das Feld *oil* mit der Operation *count* und das Feld *oil* mit der Operation *sum*), werden nur die Daten in der ersten Spalte analysiert, und die übrigen erben diese Breite + +## Beispiel {#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: { + // Spaltenbreite für diese Felder berechnen + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + auto: true, + // alle Felder analysieren + firstOnly: false + } + } +}); +~~~ + +**Verwandte Beispiele**: +- [Pivot 2. Automatische Breite. Spalten an den Inhalt anpassen](https://snippet.dhtmlx.com/tn1yw14m) +- [Pivot 2. Spaltenbreite festlegen](https://snippet.dhtmlx.com/ceu34kkn) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/config-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/config-property.md new file mode 100644 index 0000000..7d6990d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/config-property.md @@ -0,0 +1,146 @@ +--- +sidebar_label: config +title: config Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die config-Konfigurationseigenschaft. Lesen Sie Entwicklerhandbücher und API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# config + +### Beschreibung {#description} + +@short: Optional. Definiert die Struktur der Pivot-Tabelle und die Art der Datenaggregation + +### Verwendung {#usage} + +~~~jsx +config?: { + rows?: string | {field: string, method?: string}[], + columns?: string | {field: string, method?: string}[], + values?: string | {field: string, method?: string}[], + filters?: {} +}; +~~~ + +### Parameter {#parameters} + +Die `config`-Parameter legen fest, welche Felder als Zeilen und Spalten verwendet werden und welche zusätzlichen Datenaggregationsmethoden auf Zeilen/Spalten angewendet werden sollen. + +- `rows` - (optional) definiert die Zeilen der Pivot-Tabelle. Der Standardwert ist ein leeres Array. Es kann ein String sein, der eine einzelne Feld-ID repräsentiert, oder ein Objekt mit der Feld-ID und einer Methode zur Datenextraktion; die Objektparameter sind folgende: + - `field` - (erforderlich) die ID eines Feldes + - `method` - (optional) definiert eine Methode zur Datenaggregation im Feld; Methoden für zeitbasierte Datenfelder sind standardmäßig verfügbar: "year", "quarter", "month", "week", "day", "hour", "minute", die Daten entsprechend gruppieren; hier können Sie auch den Namen einer benutzerdefinierten Methode angeben ([siehe `predicates`](api/config/predicates-property.md)) für Felder beliebiger Datentypen +- `columns` - (optional) definiert Spalten für die Pivot-Tabelle. Standardmäßig ist es ein leeres Array. Es kann eine einzelne Feld-ID oder ein Objekt mit der Feld-ID und einer Methode zur Datenextraktion sein; die Objektparameter sind folgende: + - `field` - (erforderlich) die ID eines Feldes + - `method` - (optional) definiert eine Methode zur Datenverarbeitung (für zeitbasierte Datenfelder). + Standardmäßig sind Methoden für zeitbasierte Felder (Typ **date**) mit folgenden Werten verfügbar: "year", "quarter", "month", "week", "day", "hour", "minute". Hier können Sie auch den Namen einer benutzerdefinierten Methode angeben ([siehe `predicates`](api/config/predicates-property.md)) für Felder beliebiger Datentypen +- `values` - (optional) definiert die Datenaggregation für die Zellen der Pivot-Tabelle. Standardmäßig ist es ein leeres Array. Jedes Element kann ein String sein, der eine Datenfeld-ID und eine Aggregationsmethode repräsentiert, oder ein Objekt, das die Feld-ID und die Methode zur Datenaggregation enthält. Die Objektparameter sind folgende: + - `field` - (erforderlich) die ID eines Feldes + - `method` - (erforderlich) definiert eine Methode zur Datenextraktion; Informationen zu Methodentypen und deren Beschreibung finden Sie unter [Methoden anwenden](guides/working-with-data.md#default-methods) + +
+ +Optionen zur Definition von Werten + +Sie können `values` auf eine von zwei gleichwertigen Arten definieren: +- Option 1 ist ein String, der die Feld-ID repräsentiert +- Option 2 ist ein Objekt, das die Feld-ID und die Methode zur Datenaggregation enthält + +### Beispiel {#example} + +~~~jsx +values: [ + "sum(sales)", // Option 1 + { field: "sales", method: "sum" }, // Option 2 +] +~~~ + +
+ +- `filters` - (optional) legt fest, wie Daten in der Tabelle gefiltert werden; es ist ein Objekt mit Feld-IDs und einer Filterregel. Der Standardwert ist ein leeres Objekt. Die Objektparameter sind folgende: + - `field` - (optional) der Filterschlüssel, der die ID eines Feldes oder ein Array von IDs mit den Filterkriterien ist: + - `equal` - (optional) akzeptiert Zahlen, Strings und Datumswerte + - `notEqual` - (optional) akzeptiert Zahlen, Strings und Datumswerte + - `greater` - (optional) akzeptiert Zahlen und Datumswerte + - `greaterOrEqual` - (optional) akzeptiert Zahlen und Datumswerte + - `less` - (optional) akzeptiert Zahlen und Datumswerte + - `lessOrEqual` - akzeptiert Zahlen und Datumswerte + - `between` - ein Objekt mit folgenden Parametern: + - `start` - Date + - `end` - Date + - `notBetween` - ein Objekt mit folgenden Parametern: + - `start` - Date + - `end` - Date + - `contains` - akzeptiert Strings und Zahlen + - `notContains` - akzeptiert Strings und Zahlen + - `beginsWith` - akzeptiert Strings und Zahlen + - `notBeginsWith` - akzeptiert Strings und Zahlen + - `endsWith` - akzeptiert Strings und Zahlen + - `notEndsWith` - akzeptiert Strings und Zahlen + - `includes` - (optional) ein Array von Werten, die aus den bereits gefilterten angezeigt werden sollen; verfügbar für Text- und Datumswerte + +:::info +Wenn die Konfiguration von Pivot verarbeitet wird, erhalten ihre Eigenschaften zusätzliche Daten. Wenn Sie den Konfigurationszustand über die Methode [`api.getState()`](api/internal/getstate-method.md) abrufen, sieht das vollständige Objekt wie folgt aus: + +~~~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} } + } +} +~~~ + +Parameter: + +- `id` - eine eindeutige ID des verarbeiteten Feldes +- `field` - ein Feldname +- `method` - der für die Aggregation verwendete Operationsname. Eine Methode ist bei Zeilen und Spalten optional; wenn angegeben, wirkt sie als Prädikat und legt fest, wie die Felddaten vor der Aggregation vorverarbeitet werden. Bei Werten ist die Methode ein Pflichtparameter. +- `area` - der Bereich, dem das Feld hinzugefügt wird +- `base` - wird in Spalten und Zeilen für Felder mit einem Prädikat verwendet. Definiert den ursprünglichen Feldnamen, während der Feldname nach dem Muster "field_by_predicate" gebildet wird +- `label` - Text-Label +- `type` - Datentyp +::: + +### Beispiel {#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: { + // Filter für ein weiteres Feld ("title") + contains: "A" + } + } + } +}); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md new file mode 100644 index 0000000..cf8fe6e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/configpanel-property.md @@ -0,0 +1,58 @@ +--- +sidebar_label: configPanel +title: configPanel Konfiguration +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die configPanel-Konfiguration. 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. +--- + +# configPanel + +### Beschreibung {#description} + +@short: Optional. Steuert die Sichtbarkeit des Konfigurationspanels in der Benutzeroberfläche + +In der Benutzeroberfläche wird das Panel durch Klicken auf die Schaltfläche **Einstellungen ausblenden** ein- oder ausgeblendet. + +### Verwendung {#usage} + +~~~jsx +configPanel?: boolean; +~~~ + +### Parameter {#parameters} + +Die Eigenschaft kann auf **true** oder **false** gesetzt werden: + +- `true` - Standardwert, zeigt das Konfigurationspanel an +- `false` - blendet das Konfigurationspanel aus + +## Beispiel {#example} + +~~~jsx {5} +// Das Konfigurationspanel wird beim Initialisieren ausgeblendet +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" + } + ] + } +}); +~~~ + +**Verwandtes Beispiel**: [Pivot 2.0: Sichtbarkeit des Konfigurationspanels umschalten](https://snippet.dhtmlx.com/1xq1x5bo) + +**Verwandte Artikel**: +- [`show-config-panel`-Event](api/events/show-config-panel-event.md) +- [`showConfigPanel()`-Methode](api/methods/showconfigpanel-method.md) +- [Sichtbarkeit des Konfigurationspanels steuern](guides/configuration.md#controlling-visibility-of-configuration-panel) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/data-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/data-property.md new file mode 100644 index 0000000..f9666dd --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/data-property.md @@ -0,0 +1,129 @@ +--- +sidebar_label: data +title: data Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die data-Konfiguration. Lesen Sie Entwicklerhandbücher und API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# data + +### Beschreibung {#description} + +@short: Optional. Ein Array von Objekten mit Daten für die Pivot-Tabelle + +### Verwendung {#usage} + +~~~jsx +data?: []; +~~~ + +### Parameter {#parameters} + +Jedes Objekt des `data`-Arrays repräsentiert eine Zeile. Der Standardwert ist ein leeres Array. +Die `data`-Eigenschaft hat keine direkten Untereigenschaften. Jedes Objekt im Array kann jedoch eine beliebige Anzahl von Eigenschaften haben, die die Dimensionen und Werte für die Pivot-Tabelle darstellen. + +Beispiel des `data`-Arrays: + +~~~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") + }, + //weitere Daten +]; +~~~ + +### Beispiel {#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 + }, + //weitere Datenobjekte + ], + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/fields-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/fields-property.md new file mode 100644 index 0000000..fef281c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/fields-property.md @@ -0,0 +1,112 @@ +--- +sidebar_label: fields +title: fields Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die fields-Konfiguration. Entdecken 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. +--- + +# fields + +### Beschreibung {#description} + +@short: Optional. Ein Array von Objekten mit Feldern für die Pivot-Tabelle + +Die Eigenschaft `fields` im Konfigurationsobjekt steuert, wie das Widget die Typen der empfangenen Datenfelder interpretiert, und ermöglicht die Definition der Sortierreihenfolge für ein Feld. + +### Verwendung {#usage} + +~~~jsx +fields?: [{ + id: string, + label?: string, + type: "number" | "date" | "text", + sort?: "asc" | "desc" | ((a: any, b: any) => number), + format?: string | boolean | numberFormatOptions{} +}]; +~~~ + +### Parameter {#parameters} + +Wenn die Eigenschaft nicht gesetzt ist, analysiert das Widget die eingehenden Daten automatisch und befüllt das `fields`-Objekt entsprechend. + +Jedes Objekt im `fields`-Array sollte die folgenden Eigenschaften haben: + +- `id` - (erforderlich) die ID eines Feldes +- `label` - (optional) die Feldbezeichnung, die in der Benutzeroberfläche angezeigt wird +- `type` - (erforderlich) der Datentyp in einem Feld ("number", "date" oder "text") +- `sort` - (optional) legt die Standard-Sortierreihenfolge für das Feld fest. Akzeptiert "asc", "desc" oder eine benutzerdefinierte Sortierfunktion +- `format` - (optional) ermöglicht die Anpassung des Formats von Zahlen und Datumsangaben in einem Feld; das Format wird auch beim [Export](guides/exporting-data.md) angewendet + - `string` - (optional) das Format für Datumsangaben (standardmäßig verwendet Pivot `dateFormat` aus dem Locale) + - `boolean` - (optional) wenn auf **false** gesetzt, wird eine Zahl unverändert und ohne Formatierung angezeigt + - `numberFormatOptions` - (optional) ein Objekt mit Optionen zur Formatierung numerischer Felder; standardmäßig werden Zahlen mit maximal 3 Dezimalstellen angezeigt, und für den ganzzahligen Teil wird eine Gruppentrennzeichenformatierung angewendet. + - `minimumIntegerDigits`(number) - (optional) die Mindestanzahl von Vorkommastellen (wenn der Wert beispielsweise auf 2 gesetzt ist, wird die Zahl 1 als "01" angezeigt); der Standardwert ist 1; + - `minimumFractionDigits`(number) - (optional) die Mindestanzahl der zu verwendenden Nachkommastellen (wenn der Wert beispielsweise auf 2 gesetzt ist, wird die Zahl 10.5 als "10.50" angezeigt); der Standardwert ist 0; + - `maximumFractionDigits`(number) - (optional) die maximale Anzahl der zu verwendenden Nachkommastellen (wenn der Wert beispielsweise auf 2 gesetzt ist, wird die Zahl 10.3333... als "10.33" angezeigt); der Standardwert ist 3; + Weitere Details zu den Stellenoptionen finden Sie unter [Stellenoptionen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#minimumintegerdigits) + - `prefix` (string) - (optional) eine Zeichenkette (vor einer Zahl) für zusätzliche Symbole wie Währungszeichen + - `suffix` (string) - (optional) eine Zeichenkette (nach einer Zahl) für zusätzliche Symbole wie Währungszeichen + +:::info +Wenn über die Eigenschaft [`tableShape`](api/config/tableshape-property.md) ein Template angewendet wird, überschreibt dieses die `format`-Einstellungen. +::: + +### Beispiel {#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" + }, + //weitere Felder + ], + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +**Verwandte Artikel**: + +- [Zahlenformatierung](guides/localization.md#number-formatting) +- [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields) + +**Verwandtes Beispiel**: [Pivot 2. Feldformate definieren](https://snippet.dhtmlx.com/77nc4j8v) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/headershape-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/headershape-property.md new file mode 100644 index 0000000..ac9f935 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/headershape-property.md @@ -0,0 +1,83 @@ +--- +sidebar_label: headerShape +title: headerShape Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die headerShape-Konfiguration. Lesen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# headerShape + +### Beschreibung {#description} + +@short: Optional. Konfiguriert das Aussehen und das Verhalten der Kopfzeilen in der Pivot-Tabelle + +### Verwendung {#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, +}; +~~~ + +### Parameter {#parameters} + +- `collapsible` - (optional) wenn auf **true** gesetzt, sind Dimensionsgruppen in der Tabelle einklappbar. Standardmäßig ist der Wert **false** +- `vertical` - (optional) wenn auf **true** gesetzt, wird die Textausrichtung in allen Kopfzeilen von horizontal auf vertikal geändert. Der Standardwert ist **false** +- `cellStyle` - (optional) eine Funktion, die einen benutzerdefinierten Stil auf eine Kopfzeilenzelle anwendet. Die Funktion gibt den Namen einer CSS-Klasse zurück und akzeptiert folgende Parameter: + - `field` (string) - (erforderlich) ein String, der den Feldnamen angibt, dem die Zelle entspricht. Für die Kopfzeile der Baumspalte ist das Feld "" + - `value` (string | number | date) - (erforderlich) der Wert einer Zelle + - `area` - (erforderlich) ein String, der den Bereich der Tabelle angibt, in dem sich eine Zelle befindet ("rows", "columns" oder "values"-Bereich) + - `method` (string) - (optional) ein String, der die für ein Feld aus dem "values"-Bereich ausgeführte Operation (z. B. "sum", "count" usw.) oder den Namen eines für ein Feld aus dem "columns"-Bereich festgelegten Prädikats darstellen kann + - `isTotal` - (optional) gibt an, ob eine Zelle zu einer Gesamtspalte gehört +- `template` - (optional) definiert das Format des Texts in Kopfzeilen. Standardmäßig wird für Felder, die als Zeilen verwendet werden, der Wert des Parameters `label` angezeigt, und für Felder, die als Werte verwendet werden, werden Label und Methode angezeigt (z. B. *Oil(count)*). Die Funktion nimmt die Feld-ID, das Label und die Methode oder Prädikat-ID (falls vorhanden) entgegen und gibt den verarbeiteten Wert zurück. Das Standard-Template lautet wie folgt: +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +## Beispiel {#example} + +Im folgenden Beispiel wird für die **values**-Felder in der Kopfzeile das Label, der Methodenname (subLabel) angezeigt und das Ergebnis in Kleinbuchstaben umgewandelt (z. B. *profit (sum)*): + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // ein benutzerdefiniertes Template für den Kopfzeilentext + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // weitere Werte + ], + }, + fields, +}); +~~~ + +**Verwandte Beispiele**: +- [Pivot 2. Vertikale Textausrichtung in Tabellenkopfzeilen](https://snippet.dhtmlx.com/4qroi8ka) +- [Pivot 2. Einklappbare Spalten](https://snippet.dhtmlx.com/pt2ljmcm) +- [Pivot 2. Benutzerdefiniertes CSS für Tabellen- und Kopfzeilenzellen hinzufügen](https://snippet.dhtmlx.com/nfdcs4i2) + +**Verwandte Artikel**: +- [Konfiguration](guides/configuration.md) +- [Zellstil](guides/stylization.md#cell-style) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/limits-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/limits-property.md new file mode 100644 index 0000000..cb5ce75 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/limits-property.md @@ -0,0 +1,61 @@ +--- +sidebar_label: limits +title: limits Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die limits-Konfiguration. Entdecken Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# limits + +### Beschreibung {#description} + +@short: Optional. Legt die maximale Anzahl von Zeilen und Spalten im endgültigen Datensatz fest + +Weitere Informationen finden Sie unter [Datenmenge begrenzen](guides/working-with-data.md#limiting-loaded-data). + +### Verwendung {#usage} + +~~~jsx +limits?: { + rows?: number, + columns?: number, + raws?: number +}; +~~~ + +### Parameter {#parameters} + +Die Parameter legen fest, wann das Rendering der Daten unterbrochen wird: + +- `rows` - (optional) legt die maximale Anzahl von Zeilen im endgültigen Datensatz fest; der Standardwert ist 10000. +- `columns` - (optional) legt die maximale Anzahl von Spalten im endgültigen Datensatz fest; der Standardwert ist 5000. +- `raws` - (optional) die maximale Anzahl von Quelldatenzeilen vor der Gruppierung der Daten (Rohdatensätze für die Aggregation); der Standardwert ist unendlich. + +:::note +Limits werden für große Datensätze verwendet. Die Limit-Werte sind Näherungswerte und geben nicht die genauen Anzahlen von Zeilen und Spalten an. +::: + +## Beispiel {#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 } +}); +~~~ + +**Verwandtes Beispiel**: [Pivot 2. Datenlimits](https://snippet.dhtmlx.com/7ryns8oe) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/locale-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/locale-property.md new file mode 100644 index 0000000..8333139 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/locale-property.md @@ -0,0 +1,51 @@ +--- +sidebar_label: locale +title: locale Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die locale-Konfiguration. Lesen Sie Entwicklerhandbücher und API-Referenzen, testen Sie Code-Beispiele und Live-Demos und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# locale + +### Beschreibung {#description} + +@short: Optional. Ein Objekt für eine benutzerdefinierte Locale von Pivot + +### Verwendung {#usage} + +~~~jsx +locale?: object; +~~~ + +### Standardkonfiguration {#default-config} + +Standardmäßig verwendet Pivot die [englische](guides/localization.md#default-locale) Locale. Sie können auch eine benutzerdefinierte Locale festlegen. + +:::tip +Um die aktuelle Locale dynamisch zu ändern, können Sie die Methode [`setLocale()`](api/methods/setlocale-method.md) von Pivot verwenden. +::: + +### Beispiel {#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, // die Locale "cn" wird initial gesetzt + // weitere Parameter +}); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/methods-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/methods-property.md new file mode 100644 index 0000000..b50a3ee --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/methods-property.md @@ -0,0 +1,163 @@ +--- +sidebar_label: methods +title: methods Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die methods-Konfiguration. Lesen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# methods + +### Beschreibung {#description} + +@short: Optional. Definiert benutzerdefinierte mathematische Methoden für die Datenaggregation + +### Verwendung {#usage} + +~~~jsx +methods?: { + [method: string]: { + type?: 'number' | 'date' | 'text' | [], + label?: string, + handler?: (values: number[]) => number, + branchMode?: "raw"|"result", + branchMath?: string + } +}; +~~~ + +### Parameter {#parameters} + +Jede Methode wird durch ein Schlüssel-Wert-Paar dargestellt, wobei `method` der Name der Methode ist und der Wert ein Objekt ist, das das Verhalten der Methode beschreibt. Jedes Objekt verfügt über folgende Parameter: + +- `handler` - (für benutzerdefinierte Methoden erforderlich) eine Funktion, die einen aggregierten Wert aus einem Array von Zahlen berechnet; die Funktion nimmt ein Array von Werten als Eingabe entgegen und gibt einen einzelnen Wert als Ausgabe zurück +- `type` - (optional) der Datentyp, für den diese Methode geeignet ist; mögliche Werte sind "number", "date" oder "text" oder ein Array dieser Werte +- `label` - (optional) die Methodenbezeichnung, die in der Benutzeroberfläche angezeigt wird +- `branchMode` - (optional) definiert den Modus für die Berechnung von Gesamtwerten in der Baumtabelle; `branchMode` kann auf `raw` gesetzt werden, um die Berechnung auf Basis aller Rohdaten durchzuführen; `result` (Standard) wird für die Berechnung auf Basis bereits verarbeiteter Daten im Baumstruktur-Modus verwendet +- `branchMath` - (optional) der Name einer Methode zur Berechnung von Gesamtwerten im Baumstruktur-Modus; standardmäßig identisch mit dem Methodennamen (für die Methode "max" ist `branchMath` ebenfalls "max") + +Standardmäßig ist die Eigenschaft `methods` ein leeres Objekt {}, was bedeutet, dass keine benutzerdefinierten Methoden definiert sind. Die Anzahl der Untereigenschaften, die im methods-Objekt definiert werden können, ist nicht begrenzt. + +Vordefinierte Methoden: + +~~~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" } +}; +~~~ + +Die Definition jeder Methode finden Sie hier: [Methoden anwenden](guides/working-with-data.md#default-methods) + +## Beispiel {#example} + +Das folgende Beispiel zeigt, wie die Anzahl eindeutiger und durchschnittlicher Werte für den Datumstyp berechnet wird. Die Funktion **countUnique** nimmt ein Array von Zahlen (Werten) als Eingabe entgegen und berechnet mithilfe der **reduce**-Methode die genaue Anzahl eindeutiger Werte. Die Untereigenschaft **countunique_date** verfügt über einen Handler mit einer Funktion, die eindeutige Werte aus einem Array von Datumswerten ermittelt. Die Untereigenschaft **average_date** enthält einen Handler, der Durchschnittswerte aus einem Array von Datumswerten berechnet. + +~~~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; +}); + +// Datumsstring in Date-Objekt umwandeln +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" + } + ] + } +}); +~~~ + +**Verwandtes Beispiel**: [Pivot 2. Benutzerdefinierte mathematische Methoden](https://snippet.dhtmlx.com/lv90d8q2) + +**Verwandter Artikel**: [Mathematische Methoden anwenden](guides/working-with-data.md#applying-maths-methods) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/predicates-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/predicates-property.md new file mode 100644 index 0000000..fe26895 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/predicates-property.md @@ -0,0 +1,117 @@ +--- +sidebar_label: predicates +title: predicates Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die predicates-Konfiguration. Lesen Sie Entwicklerhandbücher und API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# predicates + +### Beschreibung {#description} + +@short: Optional. Stellt benutzerdefinierte Vorverarbeitungsfunktionen für die Datendimensionen (Zeilen, Spalten) bereit + +Es definiert, wie Daten geändert werden sollen, bevor sie angewendet werden. + +### Verwendung {#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 + } + } +}; +~~~ + +### Parameter {#parameters} + +Die Eigenschaft ist ein Objekt, dessen Schlüssel der Name einer benutzerdefinierten Funktion und dessen Wert ein Objekt mit den eigentlichen Funktionsdefinitionen ist. Das Predicate-Objekt kann mehrere Schlüssel-Funktions-Paare enthalten, die alle in der Pivot-Konfiguration verwendet werden können. Jedes Objekt hat die folgenden Parameter: + +- `label` - (optional) die Beschriftung eines Predicates, die in der GUI im Dropdown unter den Datenmodifikationsoptionen für eine Zeile/Spalte angezeigt wird +- `type` - (erforderlich) definiert, für welche Feldtypen dieses Predicate angewendet werden kann; mögliche Werte sind "number", "date", "text" oder ein Array dieser Werte +- `field` - (optional) die Funktion, die definiert, wie Daten für das angegebene Feld verarbeitet werden sollen; sie nimmt die ID eines Feldes als Parameter entgegen und gibt **true** zurück, wenn das Predicate dem angegebenen Feld hinzugefügt werden soll +- `filter` - (optional) standardmäßig wird der Filter-Typ aus dem Parameter `type` übernommen; wenn Sie einen anderen benötigen, können Sie dieses `filter`-Objekt verwenden. Es hat die folgenden Parameter: + - `type` - (optional) definiert, welcher Feldtyp angewendet wird: "number"|"text"|"date"|"tuple". "tuple" ist ein Combo-Filter für numerische Werte (die Daten werden nach dem numerischen Wert gefiltert, aber im Filter wird der Textwert angezeigt) + - `format` - (optional) die Funktion, die das Format für die Anzeige von Filteroptionen definiert; wenn kein Format angegeben ist, wird das Format aus dem Parameter `template` verwendet; wenn der Typ hier (für das `filter`-Objekt) nicht angegeben ist, wird das Format für den im Parameter `type` des Predicates festgelegten Typ angewendet +- `handler` - (für benutzerdefinierte Predicates erforderlich) die Funktion, die definiert, wie Daten verarbeitet werden sollen; die Funktion nimmt einen einzelnen Argumentwert entgegen und gibt den verarbeiteten Wert zurück +- `template` - (optional) die Funktion, die definiert, wie Daten angezeigt werden sollen; die Funktion gibt den verarbeiteten Wert zurück und nimmt den von `handler` zurückgegebenen Wert entgegen; bei Bedarf können Textwerte mithilfe von [`locale`](api/config/locale-property.md) lokalisiert werden. + +Die folgenden Standard-Predicates werden angewendet, wenn über die Eigenschaft `predicates` kein Predicate angegeben wird: + +~~~jsx +const defaultPredicates = { + // ein Service-Predicate, das den rohen (unverarbeiteten) Wert darstellt + $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" } } +}; +~~~ + +## Beispiel {#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"), + }, +}; + +// Datumszeichenkette in Date umwandeln +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"], + }, +}); +~~~ + +**Verwandter Artikel**: [Daten mit Predicates verarbeiten](guides/working-with-data.md#processing-data-with-predicates) + +**Verwandtes Beispiel**: [Pivot 2. Benutzerdefinierte Predicates](https://snippet.dhtmlx.com/mhymus00) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/readonly-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/readonly-property.md new file mode 100644 index 0000000..7d8698d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/readonly-property.md @@ -0,0 +1,52 @@ +--- +sidebar_label: readonly +title: readonly Config +description: Sie können mehr über die readonly-Konfiguration in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren. 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. +--- + +# readonly + +### Beschreibung {#description} + +@short: Optional. Aktiviert/deaktiviert den Nur-Lese-Modus + +Im Nur-Lese-Modus ist es nicht möglich, die Pivot-Struktur über die Benutzeroberfläche zu konfigurieren. + +### Verwendung {#usage} + +~~~jsx + readonly?: boolean; +~~~ + +### Parameter {#parameters} + +Die Eigenschaft kann auf **true** oder **false** gesetzt werden: + +- `true` - aktiviert den Nur-Lese-Modus +- `false` - Standard, deaktiviert den Nur-Lese-Modus + +## Beispiel {#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 +}); +~~~ + +**Verwandtes Beispiel**: [Pivot 2. Nur-Lese-Modus](https://snippet.dhtmlx.com/0k0mvycv) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md b/i18n/de/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md new file mode 100644 index 0000000..c148cfb --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/config/tableshape-property.md @@ -0,0 +1,131 @@ +--- +sidebar_label: tableShape +title: tableShape Config +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die tableShape-Konfiguration. 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. +--- + +# tableShape + +### Beschreibung {#description} + +@short: Optional. Konfiguriert das Aussehen der Pivot-Tabelle + +### Verwendung {#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, +}; +~~~ + +### Parameter {#parameters} + +- `templates` - (optional) ermöglicht das Festlegen von Templates für eine Zelle; es ist ein Objekt, bei dem: + - jeder Schlüssel eine Feld-ID ist + - der Wert eine Funktion ist, die einen String zurückgibt und den Zellwert sowie die Operation empfängt. Alle Spalten, die auf dem angegebenen Feld basieren, erhalten das zugehörige Template angewendet. Beispielsweise können damit Maßeinheiten gesetzt oder die gewünschte Anzahl von Nachkommastellen für numerische Werte zurückgegeben werden usw. Siehe das Beispiel unten. +- `marks` - (optional) ermöglicht das Markieren einer Zelle mit den erforderlichen Werten. Es ist ein Objekt, bei dem Schlüssel CSS-Klassennamen sind und Werte entweder eine Funktion oder einer der vordefinierten Strings ("max", "min") sind. Die Funktion soll einen booleschen Wert für den geprüften Wert zurückgeben. Wenn **true** zurückgegeben wird, wird die CSS-Klasse der Zelle zugewiesen. Weitere Informationen mit Beispielen finden Sie hier: [Zellen markieren](guides/stylization.md#cell-style). +- `sizes` - (optional) definiert die folgenden Größenparameter der Tabelle: + - `rowHeight` - (optional) die Zeilenhöhe in der Pivot-Tabelle in Pixeln. Der Standardwert ist 34 + - `headerHeight` - (optional) die Kopfzeilenhöhe in Pixeln; der Standardwert ist 30 + - `footerHeight` - (optional) die Fußzeilenhöhe in Pixeln; der Standardwert ist 30 + - `columnWidth` - (optional) die Spaltenbreite in Pixeln; der Standardwert ist 150 +- `cellStyle` - (optional) eine Funktion, die einen benutzerdefinierten Stil auf eine Zelle anwendet. Die Funktion hat die folgenden Parameter: + - `field` - (erforderlich) ein String, der den Feldnamen angibt, für den der Stil angewendet wird + - `value` - (erforderlich) der Wert der Zelle (die tatsächlichen Daten für diese bestimmte Zeile und Spalte) + - `area` - (erforderlich) ein String, der den Bereich der Tabelle angibt, in dem sich eine Zelle befindet ("rows", "columns" oder "values"-Bereich) + - `method` - (optional) ein String, der die für eine Zelle ausgeführte Operation angeben kann (z. B. "sum", "count" usw.) + - `isTotal` - (optional) gibt an, ob eine Zelle zu einer Gesamtzeile, einer Gesamtspalte oder beiden gehört: "row"|"column"|"both" + Die Funktion `cellStyle` gibt einen String zurück, der als CSS-Klassenname verwendet werden kann, um bestimmte Stile auf eine Zelle anzuwenden. +- `tree` - (optional) wenn auf **true** gesetzt, wird der Baumstruktur-Modus aktiviert, in dem Daten mit aufklappbaren Zeilen dargestellt werden können; der Standardwert ist **false**. Weitere Informationen mit Beispielen finden Sie hier: [Zum Baumstruktur-Modus wechseln](guides/configuration.md#enabling-the-tree-mode) +- `totalColumn` - (optional) wenn **true**, wird die Generierung der Gesamtspalte mit Gesamtwerten für Zeilen aktiviert (standardmäßig ist **false** gesetzt). Wenn der Wert auf "sumOnly" gesetzt wird, wird die Spalte mit dem Gesamtsummenwert generiert (nur für Summen-Operationen verfügbar) +- `totalRow` - (optional) wenn **true**, wird die Generierung der Fußzeile mit Gesamtwerten aktiviert (standardmäßig ist **false** gesetzt). Wenn der Wert auf "sumOnly" gesetzt wird, wird die Zeile mit dem Gesamtzeilenwert generiert (nur für Summen-Operationen verfügbar) +- `cleanRows` - (optional) wenn auf **true** gesetzt, werden doppelte Werte in Skalenspalten in der Tabellenansicht ausgeblendet. Der Standardwert ist **false** +- `split` - (optional) ermöglicht das Einfrieren von Spalten rechts oder links, abhängig vom angegebenen Parameter (siehe [Spalten einfrieren](guides/configuration.md#freezing-columns)): + - `left` (boolean) - wenn auf **true** gesetzt (standardmäßig ist **false** gesetzt), werden die Spalten von links fixiert, sodass die Spalten beim Scrollen statisch und sichtbar bleiben. Die Anzahl der aufgeteilten Spalten entspricht der Anzahl der Zeilenfelder, die in der Eigenschaft [`config`](api/config/config-property.md) definiert sind + - `right` (boolean) - fixiert Gesamtspalten auf der rechten Seite; Standardwert ist **false** + +Standardmäßig ist `tableShape` undefiniert, was bedeutet, dass keine Gesamtzeile, keine Gesamtspalte vorhanden ist, keine Templates und Markierungen angewendet werden, die Daten als Tabelle und nicht als Baumstruktur angezeigt werden und Spalten beim Scrollen nicht fixiert sind. + +## Beispiel {#example} + +Im folgenden Beispiel wenden wir das Template auf die *state*-Zellen an, um den kombinierten Namen eines Bundesstaates (den vollständigen Namen und die Abkürzung) anzuzeigen. + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", +// other values, +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // set a template to customize values of "state" cells + 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, +}); +~~~ + +**Verwandte Beispiele**: + +- [Pivot 2. Baumstruktur-Modus](https://snippet.dhtmlx.com/6ylkoukn) +- [Pivot 2. Eingefrorene (fixierte) Spalten](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. Zeilen-, Kopfzeilen-, Fußzeilenhöhe und Spaltenbreite festlegen](https://snippet.dhtmlx.com/x46uyfy9) +- [Pivot 2. Zeilen bereinigen](https://snippet.dhtmlx.com/rwwhgv2w?tag=pivot) +- [Pivot 2. Benutzerdefiniertes CSS für Tabellen- und Kopfzeilenzellen hinzufügen](https://snippet.dhtmlx.com/nfdcs4i2) + +**Verwandte Artikel**: +- [Konfiguration](guides/configuration.md) +- [Zellenstil](guides/stylization.md#cell-style) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/add-field-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/add-field-event.md new file mode 100644 index 0000000..60f943b --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/add-field-event.md @@ -0,0 +1,74 @@ +--- +sidebar_label: add-field +title: add-field Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das add-field-Event. Lesen Sie Entwicklerhandbücher und API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# add-field + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn ein neues Feld zum Bereich Zeilen, Spalten oder Werte hinzugefügt wird + +### Verwendung {#usage} + +~~~jsx +"add-field": ({ + id?: string | number, + area: string, + field: string | number, + method?: string +}) => boolean; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion erhält ein Objekt mit den folgenden Parametern: + +- `id` - (optional) die gewünschte ID eines neuen Feldes; wenn sie nicht festgelegt ist, wird eine automatisch generierte ID vergeben +- `area` - (erforderlich) der Name des Bereichs, dem ein neues Feld hinzugefügt wird; mögliche Werte sind "rows", "columns" oder "values" +- `field` - (erforderlich) der Name eines Feldes +- `method` - (optional) definiert eine Methode zur Datenaggregation (wenn nicht angegeben, wird die erste für diesen Datentyp geeignete Methode verwendet); eine Methode kann einer der folgenden sein: + - Für den Bereich **values** ist sie erforderlich und gibt als Zeichenkette einen der Datenoperationstypen an: [Standardmethoden](guides/working-with-data.md#default-methods) + - Für die Bereiche **rows** und **columns** ist sie optional; wenn ein Wert festgelegt ist, handelt es sich um ein Prädikat. Es kann ein benutzerdefiniertes Prädikat oder eines der Standardwerte sein: "year", "quarter", "month", "week", "day", "hour", "minute". Standardmäßig wird der Rohwert verwendet. + Wenn ein benutzerdefiniertes Prädikat oder eine benutzerdefinierte Methode festgelegt ist, muss die ID für die Eigenschaft [predicates](api/config/predicates-property.md) oder [methods](api/config/methods-property.md) angegeben werden. + +:::info +Zur Behandlung interner Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden. +::: + +### Beispiel {#example} + +Im folgenden Beispiel verwenden wir die Methode [`api.intercept()`](api/internal/intercept-method.md), um dem Wertefeld mit dem Datentyp **number** eine neue Methode hinzuzufügen: + +~~~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" + } + ] + } +}); +//Werte mit einer vordefinierten Methode hinzufügen +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"; + } +}); +~~~ + +**Verwandte Artikel**: [api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md new file mode 100644 index 0000000..36f89dc --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/apply-filter-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: apply-filter +title: apply-filter Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das apply-filter-Event. Lesen Sie Entwicklerhandbücher und die API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# apply-filter + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn ein Filter angewendet wird + +### Verwendung {#usage} + +~~~jsx +"apply-filter": ({ + rule: {} +}) => boolean | void; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion empfängt ein Objekt mit folgenden Parametern: + +- `rule` - ein beliebiges Filter-Konfigurationsobjekt mit den folgenden Parametern: + - `field` - (erforderlich) die Feld-ID, auf die der Filter angewendet wird + - `filter` - (erforderlich) Filtertyp: + - für Textwerte: equal, notEqual, contains, notContains, beginsWith, notBeginsWith, endsWith, notEndsWith + - für numerische Werte: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, contains, notContains + - für Datumstypen: greater, less, greaterOrEqual, lessOrEqual, equal, notEqual, between, notBetween + - `value` - (optional) der Wert, nach dem gefiltert werden soll + - `includes` - (optional) ein Array von Werten, die aus den bereits gefilterten Einträgen angezeigt werden sollen; verfügbar für Text- und Datumswerte + +:::info +Zur Verarbeitung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden +::: + +### Beispiel {#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" + } + ] + } +}); +//Gibt den Namen des Feldes, auf das der Filter angewendet wurde, in der Konsole aus +table.api.on("apply-filter", (ev) => { + console.log("The field to which filter was applied:", ev.rule.field); +}); +~~~ + +**Verwandte Artikel**: [api.on()](api/internal/on-method.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md new file mode 100644 index 0000000..f13a4b6 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/delete-field-event.md @@ -0,0 +1,82 @@ +--- +sidebar_label: delete-field +title: delete-field Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das delete-field-Event. Lesen Sie Entwickleranleitungen und API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus, und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# delete-field + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn ein Feld entfernt wird + +### Verwendung {#usage} + +~~~jsx +"delete-field": ({ + area: string, + id: string | number +}) => boolean | void; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion erhält ein Objekt mit den folgenden Parametern: + +- `area` - (erforderlich) der Name des Bereichs, aus dem ein Feld entfernt wird; mögliche Werte: "rows", "columns" oder "values" +- `id` - (erforderlich) die ID des Feldes, das entfernt wird + +:::info +Zur Verarbeitung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden. +::: + +### Beispiel {#example} + +Im folgenden Beispiel wird die Aktion `delete-field` über die Methode [`api.exec()`](api/internal/exec-method.md) ausgelöst. Das letzte Feld wird aus dem **values**-Bereich entfernt. Die Methode [`api.getState()`](api/internal/getstate-method.md) wird verwendet, um den aktuellen Zustand der Pivot-[`config`](api/config/config-property.md) abzurufen. Die Aktion wird durch einen Button-Klick ausgelöst. + +~~~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-Methoden aufrufen: einen bestimmten Wert aus values in config entfernen +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, // automatisch generierte ID eines zu config.values hinzugefügten Elements + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/move-field-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/move-field-event.md new file mode 100644 index 0000000..9e89a9a --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/move-field-event.md @@ -0,0 +1,65 @@ +--- +sidebar_label: move-field +title: move-field Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das move-field-Event. Lesen Sie Entwicklerhandbücher und die API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# move-field + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn Felder neu angeordnet werden + +### Verwendung {#usage} + +~~~jsx +"move-field": ({ + area: string, + id: string | number, + before?: string, + after?: string +}) => void | boolean; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion erhält ein Objekt mit den folgenden Parametern: + +- `area` - (erforderlich) der Name des Bereichs, in dem die Neuanordnung stattfindet; mögliche Werte sind „rows", „columns" oder „values" +- `id` - (erforderlich) die ID des verschobenen Feldes +- `before` - (optional) die ID des Feldes, vor dem das verschobene Feld platziert wird +- `after` - (optional) die ID des Feldes, nach dem das verschobene Feld platziert wird + +:::info +Zur Behandlung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden +::: + +### Beispiel {#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" + } + ] + } +}); + +//die ID des neu angeordneten Feldes in der Konsole ausgeben +table.api.on("move-field", (ev) => { + console.log("The id of the reordered field:", ev.id); +}); +~~~ + +**Verwandte Artikel**: [api.on()](api/internal/on-method.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md new file mode 100644 index 0000000..2b19b8a --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/open-filter-event.md @@ -0,0 +1,95 @@ +--- +sidebar_label: open-filter +title: open-filter Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das open-filter-Event. Lesen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# open-filter + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn ein Filter für ein Feld aktiviert wird + +### Verwendung {#usage} + +~~~jsx +"open-filter": ({ + id: string | null, + area?: "values" | "rows" | "columns" +}) => boolean | void; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion nimmt die folgenden Parameter entgegen: + +- `area` - der Bereich, in dem ein Feld angewendet wird ("rows", "columns", "values") +- `id` - die ID eines Feldes; wenn es ein einzelnes id-Argument mit dem Wert null gibt, wird der Filter geschlossen. + +:::info +Für die Verarbeitung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden. +::: + +### Rückgabewert {#returns} + +Die Funktion kann entweder einen booleschen Wert oder void zurückgeben. Wenn sie **false** zurückgibt, wird die betreffende Event-Operation angehalten. + +### Beispiel {#example} + +Das folgende Beispiel zeigt, wie das Konfigurationsfenster beim Schließen der Filterbox ausgeblendet werden kann: + +~~~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 + }); + } +}); +~~~ + +Im nächsten Beispiel wird die ID des Feldes, für das der Filter aktiviert ist, in der Konsole ausgegeben: + +~~~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("Die Feld-ID, für die der Filter aktiviert ist:", ev.id); +}); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/render-table-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/render-table-event.md new file mode 100644 index 0000000..7c884fe --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/render-table-event.md @@ -0,0 +1,178 @@ +--- +sidebar_label: render-table +title: render-table Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das render-table-Event. Entwicklerhandbücher und API-Referenz, Code-Beispiele und Live-Demos sowie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot. +--- + +# render-table + +### Beschreibung {#description} + +@short: Wird ausgelöst, nachdem die Widget-Konfiguration verarbeitet wurde und unmittelbar bevor die Tabelle gerendert wird + +Es ermöglicht Ihnen, die endgültige Tabellenkonfiguration spontan zu ändern oder das Rendering der Tabelle vollständig zu verhindern. + +### Verwendung {#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; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion erhält das `config`-Objekt mit den folgenden Parametern: + +- `columns` - (optional) Spalten-Array mit den folgenden Parametern für jedes Objekt: + - `id` (number) - (erforderlich) die ID einer Spalte + - `cell` (any) - (optional) ein Template mit dem Zellinhalt (siehe [Hinzufügen von Templates über den template-Helper](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (optional) das Template, das über die [`tableShape`](api/config/tableshape-property.md)-Eigenschaft definiert wird + - `fields` (array) - (optional) definiert Felder in der hierarchischen Spalte im Baumstruktur-Modus. Gibt die auf verschiedenen Ebenen in dieser Spalte angezeigten Felder an + - `field` - (optional) ein String, der die ID eines Feldes darstellt + - `method` (string) - (optional) eine Methode, sofern für ein Feld in dieser Spalte definiert + - `methods` (array) - (optional) definiert Methoden, die auf Felder in der hierarchischen Spalte im Baumstruktur-Modus angewendet werden + - `format` (string or object) - (erforderlich) Datumsformat oder Zahlenformat (siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields)) + - `isNumeric` (boolean) - (optional) legt fest, ob eine Spalte numerische Werte enthält + - `isTotal` (boolean) - (optional) legt fest, ob es sich um eine Gesamtsummen-Spalte handelt + - `area` (string) - (optional) der Bereich, in dem die Spalte gerendert wird: "rows", "columns", "values" + - `header` - (optional) ein Array von Header-Zellen mit den folgenden Eigenschaften für jede Zelle: + - `text` (string) - (optional) Zellentext, formatierter Wert oder mit einem Prädikat-Template verarbeiteter Wert + - `rowspan` (number) - (optional) die Anzahl der Zeilen, über die sich ein Header erstreckt + - `colspan` (number) - (optional) die Anzahl der Spalten, über die sich ein Header erstreckt + - `value` (any) - (erforderlich) Rohwert, wenn eine Zelle zum Bereich "columns" gehört + - `field` (string) - (erforderlich) ein Feld, dessen Wert angezeigt wird, wenn eine Zelle zum Bereich "columns" gehört + - `method` (string) - (erforderlich) das Feld-Prädikat, wenn eine Zelle zum Bereich "columns" gehört und ein Prädikat definiert ist + - `format` (string or object) - Datumsformat oder Zahlenformat (siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields)) + - `footer` - (optional) ein Header-Label oder ein Objekt mit Footer-Einstellungen, die den Header-Einstellungen entsprechen + - `data` - (optional) ein Array von Objekten mit Daten für die Tabelle; jedes Objekt repräsentiert eine Zeile: + - `id` (number) - (erforderlich) Zeilen-ID + - `values` (array) - (erforderlich) ein Array mit Zeilendaten + - `open` (boolean) - (optional) Zustand eines Zweigs + - `$level` (boolean) - (optional) Index eines Zweigs +- `footer` - (optional) wenn auf **true** gesetzt, wird der Tabellen-Footer am unteren Rand der Tabelle angezeigt; standardmäßig auf **false** gesetzt und nicht sichtbar +- `sizes` - (optional) ein Objekt mit Einstellungen für Tabellengrößen, nämlich columnWidth, footerHeight, headerHeight, rowHeight +- `split` (object) - (optional) ein Objekt mit den folgenden Eigenschaften: + - `left` (number) - die Anzahl der fixierten Spalten von links + - `right` (number) - die Anzahl der fixierten Spalten von rechts +- `tree` - (optional) legt fest, ob der Baumstruktur-Modus aktiviert ist (**true**, wenn aktiviert) +- `cellStyle` - (optional) eine Funktion, die einen benutzerdefinierten Stil auf eine Zelle anwendet. Sie empfängt die Zeilen- und Spaltenobjekte und gibt einen String mit einem CSS-Klassenname zurück: `(row, col) => string` + +:::info +Zur Verarbeitung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden +::: + +### Rückgabewert {#returns} + +Der Callback kann einen booleschen Wert oder void zurückgeben. +Wenn der Event-Handler **false** zurückgibt, wird die betreffende Operation blockiert. In diesem Fall wird das Rendering der Tabelle verhindert. + +### Beispiel {#example} + +Das folgende Beispiel zeigt, wie das [`config`](api/config/config-property.md)-Objekt in der Konsole ausgegeben und ein Footer hinzugefügt wird. + +~~~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); //gibt das config-Objekt aus + console.log(ev.config.columns); //gibt das columns-Array aus + + ev.config.footer = true; + ev.config.columns[0].footer = ["Custom footer"]; + + // die Rückgabe von "false" verhindert das Rendering der Tabelle +}); +~~~ + +Das folgende Beispiel zeigt, wie alle Zeilen per Klick auf einen Button ein- und ausgeklappt werden können. Der Baumstruktur-Modus muss über die [`tableShape`](api/config/tableshape-property.md)-Eigenschaft aktiviert werden. + +~~~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(); + +// alle Tabellenzweige beim Aktualisieren der Tabellenkonfiguration schließen +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // die Rückgabe von "false" verhindert das Rendering der Tabelle + // return false; +}); + +function openAll() { + tableApi.exec("open-row", { id: 0, nested: true }); +} + +function closeAll() { + tableApi.exec("close-row", { id: 0, nested: true }); +} +~~~ + +Lesen Sie auch, wie Sie das Split-Feature mithilfe des `render-table`-Events konfigurieren: [Spalten fixieren](guides/configuration.md#freezing-columns). + +**Verwandter Artikel**: [pivot.template-Helper](api/helpers/template.md) + +**Verwandtes Beispiel**: [Pivot 2. Benutzerdefinierte fixierte Spalten (eigene Anzahl)](https://snippet.dhtmlx.com/53erlmgp) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/show-config-panel-event.md new file mode 100644 index 0000000..ce0c58f --- /dev/null +++ b/i18n/de/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 Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das show-config-panel Event. 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. +--- + +# show-config-panel + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn sich die Sichtbarkeit des Konfigurationspanels ändert + +### Verwendung {#usage} + +~~~jsx +"show-config-panel": ({ + mode: boolean +}) +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion nimmt ein Objekt mit dem folgenden Parameter entgegen: + +- `mode` - (erforderlich) wenn der Wert auf **true** gesetzt ist (Standard), wird das Konfigurationspanel angezeigt; wenn er auf **false** gesetzt ist, wird das Konfigurationspanel ausgeblendet + +:::info +Zur Verarbeitung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden +::: + +### Beispiel {#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" + } + ] + } +}); +//Konfigurationspanel ausblenden +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +**Verwandte Artikel**: +- [Methode `showConfigPanel()`](api/methods/showconfigpanel-method.md) +- [Eigenschaft `configPanel`](api/config/configpanel-property.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/update-config-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/update-config-event.md new file mode 100644 index 0000000..b420844 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/update-config-event.md @@ -0,0 +1,78 @@ +--- +sidebar_label: update-config +title: update-config Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie alles über das update-config-Event. Erkunden Sie Entwicklerhandbücher und API-Referenzen, testen Sie Code-Beispiele und Live-Demos und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# update-config + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn Zeilen, Spalten oder Aggregationsfunktionen über die Pivot-Benutzeroberfläche geändert werden + +Die Aktion ist nützlich, um die Aggregationskonfiguration eines Benutzers zu speichern, damit sie beim nächsten Verwenden des Widgets angewendet werden kann und der Benutzer dort fortfahren kann, wo er aufgehört hat. + +### Verwendung {#usage} + +~~~jsx +"update-config": ({ + rows: string[], + columns: string[], + values: [], + filters: {} +}) => boolean | void; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion nimmt ein Objekt mit den verarbeiteten [`config`](api/config/config-property.md)-Parametern entgegen: + +- `rows` - Zeilen der Pivot-Tabelle. Ein Objekt mit der Feld-ID und einer Methode zur Datenextraktion; die Objektparameter sind folgende: + - `field` - die ID eines Feldes + - `method` - eine Methode zur Datenextraktion (für zeitbasierte Datenfelder) +- `columns` - definiert die Spalten der Pivot-Tabelle. Es handelt sich um ein Objekt mit der Feld-ID und einer Methode zur Datenextraktion; die Objektparameter sind folgende: + - `field` - die ID eines Feldes + - `method` - definiert eine Methode zur Datenextraktion (für zeitbasierte Datenfelder). + Standardmäßig stehen Methoden für zeitbasierte Felder (Typ **date**) mit folgenden Werten zur Verfügung: "year", "quarter", "month", "week", "day", "hour", "minute" +- `values` - definiert die Datenaggregation für die Zellen der Pivot-Tabelle. Es handelt sich um ein Objekt, das die Feld-ID und die Methode zur Datenaggregation enthält. Die Objektparameter sind folgende: + - `field` - die ID eines Feldes + - `method` - definiert eine Methode zur Datenextraktion; zu Methoden und möglichen Optionen siehe [Methoden anwenden](guides/working-with-data.md#default-methods) +- `filters` - (optional) definiert, wie Daten in der Tabelle gefiltert werden; es handelt sich um ein Objekt mit Feld-IDs und der Datenaggregationsmethode. Die Beschreibung des `filter`-Objekts finden Sie hier: [`config`](api/config/config-property.md) + +:::info +Zur Verarbeitung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden. +::: + +### Rückgabewert {#returns} + +Der Callback kann einen booleschen Wert oder void zurückgeben. +Gibt die Event-Handler-Funktion *false* zurück, wird die Operation, die das Event ausgelöst hat, blockiert und der `update-config`-Vorgang wird angehalten. + +### Beispiel {#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" + } + ] + } +}); +//das Config-Objekt in die Konsole ausgeben +table.api.on("update-config", (config) => { + console.log("Config has changed", config); +}); +~~~ + +**Verwandte Artikel**: [api.intercept()](api/internal/intercept-method.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/events/update-field-event.md b/i18n/de/docusaurus-plugin-content-docs/current/api/events/update-field-event.md new file mode 100644 index 0000000..fe540bd --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/events/update-field-event.md @@ -0,0 +1,67 @@ +--- +sidebar_label: update-field +title: update-field Event +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das update-field-Event. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# update-field + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn ein Feld aktualisiert wird + +### Verwendung {#usage} + +~~~jsx +"update-field": ({ + id: string | number, + method: string, + area: string +}) => boolean; +~~~ + +### Parameter {#parameters} + +Der Callback der Aktion erhält ein Objekt mit den folgenden Parametern: + +- `id` - (erforderlich) die ID des Feldes, das aktualisiert wird +- `method` - (erforderlich) die Methode kann einen der folgenden Werte annehmen: + - Für den **values**-Bereich ist es ein String mit einem der Datenoperationstypen: [Standardmethoden](guides/working-with-data.md#default-methods) + - Für die Bereiche **rows** und **columns** kann es ein Datenprädikatwert mit einem der folgenden Werte sein: "year", "quarter", "month", "week", "day", "hour", "minute". Standardmäßig wird der Rohwert gesetzt. + Wenn ein benutzerdefiniertes Prädikat oder eine benutzerdefinierte Methode gesetzt ist, muss die ID für die Eigenschaft [predicate](api/config/predicates-property.md) oder [methods](api/config/methods-property.md) angegeben werden. +- `area` - (erforderlich) der Name des Bereichs, in dem ein Feld aktualisiert wird; mögliche Werte sind "rows", "columns" oder "values" + +:::info +Zur Behandlung der internen Events können Sie die [Event-Bus-Methoden](api/overview/internal-eventbus-overview.md) verwenden. +::: + +### Beispiel {#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" + } + ] + } +}); +//die ID des aktualisierten Feldes in der Konsole ausgeben +table.api.on("update-field", (ev) => { + console.log("The id of the field that was updated:", ev.id); +}); +~~~ + +**Verwandte Artikel**: +- [api.on()](api/internal/on-method.md) +- [Methoden](api/config/methods-property.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/helpers/template.md b/i18n/de/docusaurus-plugin-content-docs/current/api/helpers/template.md new file mode 100644 index 0000000..91d87cf --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/helpers/template.md @@ -0,0 +1,89 @@ +--- +sidebar_label: template +title: template +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über den Pivot-Template-Helper. Entwicklerhandbücher und API-Referenz, Code-Beispiele und Live-Demos sowie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot. +--- + +### Beschreibung {#description} + +Die Funktion `template` ermöglicht es, ein Template auf die Kopf- und Datenzellen der Tabelle anzuwenden. + +### Verwendung {#usage} + +Für Datenzellen: + +~~~jsx +pivot.template({value, method, row, column}) => string; +~~~ + +Für Kopfzellen: + +~~~jsx +pivot.template({value, field, method, cell, column}) => string; +~~~ + +### Parameter {#parameters} + +Für Datenzellen akzeptiert die Funktion die folgenden Parameter: + +- `value` (any) - (erforderlich) roher Zellenwert +- `method` (string) - (erforderlich) eine Methode oder ein Prädikat, das für eine Spalte verwendet wird +- `row` - (erforderlich) ein Objekt mit Zeilendaten: + - `id` (number) - (erforderlich) Zeilen-ID + - `values` (array) - (erforderlich) ein Array mit Zeilendaten + - `open` (boolean)- (optional) Zweigstatus + - `$level` (boolean)- (optional) Zweigindex +- `column` - (erforderlich) ein Objekt mit Spaltendaten: + - `id` (number) - (erforderlich) die ID einer Spalte + - `cell` (any) - (optional) ein Template mit dem Zellinhalt (siehe [Templates über den Template-Helper hinzufügen](guides/configuration.md#adding-a-template-via-the-template-helper)) + - `template` - (optional) das Template, das über die Eigenschaft [`tableShape`](api/config/tableshape-property.md) definiert wird + - `fields` (array) - (optional) definiert Felder in der hierarchischen Spalte im Baumstruktur-Modus. Gibt die Felder an, die in dieser Spalte auf verschiedenen Ebenen angezeigt werden + - `field` - (optional) eine Zeichenkette, die die ID eines Felds darstellt + - `method` (string) - (optional) eine Methode, sofern für ein Feld in dieser Spalte definiert + - `methods` (array) - (optional) definiert Methoden, die auf Felder in der hierarchischen Spalte im Baumstruktur-Modus angewendet werden + - `format` (string or object) - (erforderlich) Datumsformat oder Zahlenformat (siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields)) + - `isNumeric` (boolean) - (optional) gibt an, ob eine Spalte numerische Werte enthält + - `isTotal` (boolean) - (optional) gibt an, ob es sich um eine Gesamtspalte handelt + - `area` (string) - (optional) der Bereich, in dem die Spalte gerendert wird: "rows", "columns", "values" + - `header`- (optional) ein Array von Kopfzellen mit den folgenden Eigenschaften für jede Zelle: + - `text` (string) - (optional) Zellentext, formatierter Wert oder mit einem Prädikat-Template verarbeiteter Wert + - `rowspan` (number) - (optional) die Anzahl der Zeilen, die eine Kopfzeile überspannen soll + - `colspan` (number) - (optional) die Anzahl der Spalten, die eine Kopfzeile überspannen soll + - `value` (any) - (erforderlich) roher Wert, wenn eine Zelle zum Bereich "columns" gehört + - `field` (string) - (erforderlich) ein Feld, dessen Wert angezeigt wird, wenn eine Zelle zum Bereich "columns" gehört + - `method` (string) - (erforderlich) das Feld-Prädikat, wenn eine Zelle zum Bereich "columns" gehört und ein Prädikat definiert ist + - `format` (string or object) - Datumsformat oder Zahlenformat (siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields)) + +Für Kopfzellen sind die Funktionsparameter wie folgt: + +- `value` (any) - (erforderlich) roher Zellenwert +- `method` (string) - (optional) ein Prädikat, das für eine Spalte verwendet wird +- `field` (string) - (optional) ein Feld, dessen Wert in einer Zelle angezeigt wird +- `cell` - (erforderlich) ein Objekt mit Zellendaten: + - `text` (string) - (optional) Zellentext, formatierter Wert oder mit einem Prädikat-Template verarbeiteter Wert + - `rowspan` (number) - (optional) die Anzahl der Zeilen, die eine Kopfzeile überspannen soll + - `colspan` (number) - (optional) die Anzahl der Spalten, die eine Kopfzeile überspannen soll + - `value` (any) - (erforderlich) roher Wert, wenn eine Zelle zum Bereich "columns" gehört + - `field` (string) - (erforderlich) ein Feld, dessen Wert angezeigt wird, wenn eine Zelle zum Bereich "columns" gehört + - `method` (string) - (erforderlich) ein Feld-Prädikat, wenn eine Zelle zum Bereich "columns" gehört und ein Prädikat definiert ist + - `format` (string or object) - (erforderlich) Datumsformat oder Zahlenformat (siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields)) +- `column` - (erforderlich) ein Objekt mit Spaltendaten (identisch mit dem für die Datenzelle) + +### Beispiel {#example} + +Das folgende Snippet zeigt, wie Templates über den `pivot.template`-Helper definiert werden. Der Helper wird unmittelbar vor dem Rendern der Tabelle angewendet, indem das Ereignis [render-table](api/events/render-table-event.md) mithilfe der Methode [api.intercept()](api/internal/intercept-method.md) abgefangen wird. + +Das Snippet demonstriert, wie Sie Symbole hinzufügen können zu: + +- Datenzellen basierend auf ihrem Feld (id, user_score) (das Template fügt Flaggen- und Stern-Symbole hinzu) +- den Kopfzellen-Labels basierend auf dem Feldnamen (zum Beispiel wird bei dem Feld "id" das Globus-Symbol neben dem Kopfzellenwert hinzugefügt) +- den Spaltenköpfen basierend auf dem Wert (farbige Pfeil-Indikatoren werden hinzugefügt) + + + + +**Verwandte Artikel**: + +- [`render-table`](api/events/render-table-event.md) +- [Templates auf Zellen anwenden](guides/configuration.md#applying-templates-to-cells) +- [Templates auf Kopfzeilen anwenden](guides/configuration.md#applying-templates-to-headers) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/detach-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/detach-method.md new file mode 100644 index 0000000..60c4a81 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/detach-method.md @@ -0,0 +1,69 @@ +--- +sidebar_label: api.detach() +title: detach-Methode +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die detach-Methode. Lesen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.detach() + +## Beschreibung {#description} + +@short: Ermöglicht das Entfernen/Abtrennen von Action-Handlern + +## Verwendung {#usage} + +~~~jsx +api.detach(tag: number | string ): void; +~~~ + +## Parameter {#parameters} + +- `tag` - der Name des Action-Tags + +### Beispiel {#example} + +Im folgenden Beispiel fügen wir dem [`api.on()`](api/internal/on-method.md)-Handler ein Objekt mit der **tag**-Eigenschaft hinzu und verwenden anschließend die Methode `api.detach()`, um das Protokollieren der [`open-filter`](api/events/open-filter-event.md)-Action zu beenden. + +~~~jsx {31-34} +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// Handler hinzufügen +if (table.api) { + table.api.on( + "open-filter", + ({ area }) => { + console.log("Opened: " + area); + }, + { tag: "track" } + ); +} + +// Handler abtrennen +function stop() { + table.api.detach("track"); +} + +const button = document.createElement("button"); + +button.addEventListener("click", stop); +button.textContent = "Protokollierung beenden"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/exec-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/exec-method.md new file mode 100644 index 0000000..67b43b4 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/exec-method.md @@ -0,0 +1,83 @@ +--- +sidebar_label: api.exec() +title: exec-Methode +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die exec-Methode. Lesen Sie Entwickleranleitungen und API-Referenzen, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.exec() + +### Beschreibung {#description} + +@short: Ermöglicht das Auslösen interner Events + +## Verwendung {#usage} + +~~~jsx +api.exec( + event: string, + config: object +): Promise; +~~~ + +## Parameter {#parameters} + +- `event` - (erforderlich) ein auszulösendes Event +- `config` - (erforderlich) das Konfigurationsobjekt mit Parametern (siehe das auszulösende Event) + +## Aktionen {#actions} + +:::info +Die vollständige Liste der Pivot-Events finden Sie [**hier**](api/overview/events-overview.md) +::: + +## Beispiel {#example} + +Im folgenden Beispiel wird das [`delete-field`](api/events/delete-field-event.md)-Event über die Methode `api.exec()` ausgelöst. Das letzte Feld wird aus dem **values**-Bereich entfernt. Die Methode [`api.getState()`](api/internal/getstate-method.md) wird hier verwendet, um den aktuellen Zustand der Pivot-[`config`](api/config/config-property.md) abzurufen. Das Event wird beim Klick auf die Schaltfläche ausgelöst. + +~~~jsx {32-35} +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//API-Methoden aufrufen: einen bestimmten Wert aus values in config entfernen +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, // automatisch generierte ID eines zu config.values hinzugefügten Elements + }); + } + } +} + +const button = document.createElement("button"); + +button.addEventListener("click", removeLastField); +button.textContent = "Remove"; + +document.body.appendChild(button); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md new file mode 100644 index 0000000..9db89bd --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getreactivestate-method.md @@ -0,0 +1,71 @@ +--- +sidebar_label: api.getReactiveState() +title: getReactiveState-Methode +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die getReactiveState-Methode. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.getReactiveState() + +### Beschreibung {#description} + +@short: Gibt ein Objekt mit den reaktiven Eigenschaften von Pivot zurück + +### Verwendung {#usage} + +~~~jsx +api.getReactiveState(): object; +~~~ + +### Rückgabewert {#returns} + +Die Methode gibt ein Objekt mit den folgenden Parametern zurück: + +~~~jsx +{ + config: {}, // aktuelle Konfiguration (Zeilen, Spalten, Werte, Filter) + activeFilter: {}, // aktives Filter-Objekt (sofern ein Filter geöffnet ist) + columnShape: {}, // Konfiguration der Pivot-Spalten + data: [], // Quelldaten + fields: [], // Felder-Array + filters: {}, // Filterregeln + headerShape: {}, // Einstellungen des Tabellenkopfes + predicates: {}, // verfügbare Prädikate nach Feldern + limits: {}, // das maximale Limit für die Anzahl von Zeilen und Spalten im Datensatz + methods: {}, // Methoden zur Datenaggregation + tableShape: {}, // Tabelleneinstellungen (Größen, Gesamtzeile, Vorlagen) + tableConfig: {}, // Tabellenkonfigurationseinstellungen (Spalten, Daten, Größen, Baumansicht, Fußzeile) + configPanel: boolean, // der Sichtbarkeitsstatus des Konfigurationspanels + readonly: boolean, // ob der Nur-Lese-Modus aktiviert ist +} +~~~ + +### Beispiel {#example} + +~~~jsx {21-26} +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// den reaktiven Konfigurations-Store abonnieren und bei jeder Änderung protokollieren +const state = table.api.getReactiveState(); + +state.config.subscribe((config) => { + console.log("Pivot config changed. Its current state:", config); +}); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md new file mode 100644 index 0000000..2419186 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getstate-method.md @@ -0,0 +1,67 @@ +--- +sidebar_label: api.getState() +title: getState-Methode +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die getState-Methode. Erkunden Sie Entwicklerleitfäden und API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.getState() + +### Beschreibung {#description} + +@short: Gibt ein Objekt mit den StateStore-Eigenschaften von Pivot zurück + +### Verwendung {#usage} + +~~~jsx +api.getState(): object; +~~~ + +### Rückgabewert {#returns} + +Die Methode gibt ein Objekt mit folgenden Parametern zurück: + +~~~jsx +{ + config: {}, // aktuelle Konfiguration (rows, columns, values, filters) + activeFilter: {}, // aktives Filter-Objekt (sofern ein Filter geöffnet ist) + columnShape: {}, // Konfiguration der Pivot-Spalten + data: [], // Quelldaten + fields: [], // Felder-Array + filters: {}, // Filterregeln + headerShape: {}, // Einstellungen des Tabellen-Headers + predicates: {}, // verfügbare Prädikate je Feld + limits: {}, // maximales Limit für die Anzahl der Zeilen und Spalten im Datensatz + methods: {}, // Methoden zur Datenaggregation + tableShape: {}, // Tabellen-Einstellungen (Größen, Gesamtzeile, Templates) + tableConfig: {}, // Tabellen-Konfigurationseinstellungen (Spalten, Daten, Größen, Baumansicht, Fußzeile) + configPanel: boolean, // Status der Sichtbarkeit des Konfigurationspanels + readonly: boolean, // ob der schreibgeschützte Modus aktiviert ist +} +~~~ + +### Beispiel {#example} + +~~~jsx {21-22} +// Pivot erstellen +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); //den Konfigurations-State in der Konsole ausgeben +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md new file mode 100644 index 0000000..76a0c22 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/getstores-method.md @@ -0,0 +1,54 @@ +--- +sidebar_label: api.getStores() +title: getStores-Methode +description: Sie können mehr über die getStores-Methode in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren. Durchsuchen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.getStores() + +### Beschreibung {#description} + +@short: Gibt ein Objekt mit den DataStore-Eigenschaften von Pivot zurück + +### Verwendung {#usage} + +~~~jsx +api.getStores(): object; +~~~ + +### Rückgabewert {#returns} + +Die Methode gibt ein Objekt mit den **DataStore**-Parametern zurück: + +~~~jsx +{ + data: DataStore // ( Objekt mit Parametern ) +} +~~~ + +### Beispiel {#example} + +~~~jsx {21-22} +// Pivot erstellen +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/de/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md new file mode 100644 index 0000000..a804b99 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/intercept-method.md @@ -0,0 +1,68 @@ +--- +sidebar_label: api.intercept() +title: intercept-Methode +description: Sie können mehr über die intercept-Methode in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren. Lesen Sie Entwickleranleitungen und API-Referenzen, testen Sie Code-Beispiele und Live-Demos, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.intercept() + +### Beschreibung {#description} + +@short: Ermöglicht das Abfangen und Verhindern interner Events + +### Verwendung {#usage} + +~~~jsx +api.intercept( + event: string, + callback: function, + config?: { tag?: number | string | symbol } +): void; +~~~ + +### Parameter {#parameters} + +- `event` - (erforderlich) ein auszulösendes Event +- `callback` - (erforderlich) ein auszuführender Callback (die Callback-Argumente hängen vom ausgelösten Event ab) +- `config` - (optional) ein Objekt, das den folgenden Parameter enthält: + - `tag` - (optional) ein Aktions-Tag. Sie können den Tag-Namen verwenden, um einen Aktions-Handler über die [`detach`](api/internal/detach-method.md)-Methode zu entfernen + +### Events {#events} + +:::info +Die vollständige Liste der internen Pivot-Events finden Sie [**hier**](api/overview/main-overview.md#pivot-events). +Verwenden Sie die Methode [`api.on()`](api/internal/on-method.md), wenn Sie auf die Aktionen lauschen möchten, ohne sie zu verändern. Um Änderungen an den Aktionen vorzunehmen, verwenden Sie die Methode `api.intercept()`. +::: + +### Beispiel {#example} + +Das Beispiel zeigt, wie alle einklappbaren Zeilen beim Initialisieren geschlossen werden. + +~~~jsx {21-24} +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +//alle Zeilen beim Initialisieren schließen +table.api.intercept("render-table", (ev) => { + ev.config.data.forEach((row) => (row.open = false)); +}, {tag: "render-table-tag"}); +~~~ + +**Verwandte Artikel**: [`render-table`](api/events/render-table-event.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/on-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/on-method.md new file mode 100644 index 0000000..d54f883 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/on-method.md @@ -0,0 +1,72 @@ +--- +sidebar_label: api.on() +title: on-Methode +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die on-Methode. Lesen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.on() + +### Beschreibung {#description} + +@short: Ermöglicht das Anhängen eines Handlers an interne Events + +### Verwendung {#usage} + +~~~jsx +api.on( + event: string, + handler: function, + config?: { intercept?: boolean, tag?: number | string | symbol } +): void; +~~~ + +### Parameter {#parameters} + +- `event` - (erforderlich) ein Event, das ausgelöst werden soll +- `handler` - (erforderlich) ein anzuhängender Handler (die Handler-Argumente hängen vom ausgelösten Event ab) +- `config` - (optional) ein Objekt mit den folgenden Parametern: + - `intercept` - (optional) wenn Sie beim Erstellen des Event-Listeners `intercept: true` setzen, wird dieser Event-Listener vor allen anderen ausgeführt + - `tag` - (optional) ein Aktions-Tag. Sie können den Tag-Namen verwenden, um einen Aktions-Handler über die [`detach`](api/internal/detach-method.md)-Methode zu entfernen + +### Events {#events} + +:::info +Die vollständige Liste der internen Pivot-Events finden Sie [**hier**](api/overview/main-overview.md#pivot-events). +Verwenden Sie die Methode `api.on()`, wenn Sie auf Aktionen lauschen möchten, ohne diese zu ändern. Um Änderungen an Aktionen vorzunehmen, wenden Sie die Methode [`api.intercept()`](api/internal/intercept-method.md) an. +::: + +### Beispiel {#example} + +Das folgende Beispiel zeigt, wie die Bezeichnung eines Feldes ausgegeben wird, für das der Filter aktiviert wurde: + +~~~jsx {21-29} +// Pivot erstellen +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("Das Feld, für das der Filter aktiviert wurde:", fieldObj.label); + } + } +}, {tag: "open-filter-tag"}); +~~~ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md new file mode 100644 index 0000000..840c544 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/internal/setnext-method.md @@ -0,0 +1,45 @@ +--- +sidebar_label: api.setNext() +title: setNext Methode +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die setNext-Methode. Lesen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# api.setNext() + +### Beschreibung {#description} + +@short: Ermöglicht das Hinzufügen einer Aktion in die Event-Bus-Reihenfolge + +### Verwendung {#usage} + +~~~jsx +api.setNext(next: any): void; +~~~ + +### Parameter {#parameters} + +- `next` - (erforderlich) die Aktion, die in die **Event Bus**-Reihenfolge aufgenommen werden soll + +### Beispiel {#example} + +Das folgende Beispiel zeigt, wie die Methode `api.setNext()` verwendet wird, um eine benutzerdefinierte Klasse in die Event-Bus-Reihenfolge zu integrieren: + +~~~jsx {13-14} +const table = new pivot.Pivot("#root", { fields: [], data: [] }); +const server = "https://some-backend-url"; + +// Angenommen, Sie haben eine benutzerdefinierte Server-Service-Klasse namens 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 }); + + // Den serverDataService in die Event-Bus-Reihenfolge des Widgets integrieren + table.api.setNext(someServerService); +}); +~~~ + +**Verwandte Artikel**: [`setConfig`](api/methods/setconfig-method.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md new file mode 100644 index 0000000..7a34b8d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/gettable-method.md @@ -0,0 +1,75 @@ +--- +sidebar_label: getTable() +title: getTable-Methode +description: Sie können mehr über die getTable-Methode in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# getTable() + +### Beschreibung {#description} + +@short: Gewährt Zugriff auf die zugrundeliegende Table-Widget-Instanz in der Pivot-Tabelle + +Diese Methode wird verwendet, wenn auf die zugrundeliegende Table-Widget-Instanz in Pivot zugegriffen werden muss. Sie bietet direkten Zugriff auf die Table-Funktionalität und ermöglicht Operationen wie die Datenserialisierung und den Export in verschiedene Formate. Die Table-API verfügt über eine eigene `api.exec()`-Methode, die die Ereignisse [`open-row`](api/table/open-row.md), [`close-row`](api/table/close-row.md), [`export`](api/table/export.md) und [`filter-rows`](api/table/filter-rows.md) aufrufen kann. + +### Verwendung {#usage} + +~~~jsx +getTable(wait:boolean): Table | Promise; +~~~ + +### Parameter {#parameters} + +`wait` - legt fest, ob gewartet werden soll, bis die Table-API in Pivot verfügbar ist (notwendig, wenn die Table-API während der Pivot-Initialisierung verwendet wird). Wenn der Wert auf **true** gesetzt ist, gibt die Methode ein Promise mit der Table-API zurück. + +### Beispiel {#example} + +Im folgenden Beispiel erhalten wir Zugriff auf die Table-Widget-API und lösen das Table-`export`-Ereignis per Button-Klick mit der Methode [`api.exec()`](api/internal/exec-method.md) aus. + +~~~jsx +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// Auf Table-Instanz zugreifen +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); +~~~ + +**Verwandte Artikel**: + +- [`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/de/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md new file mode 100644 index 0000000..93c2d47 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/setconfig-method.md @@ -0,0 +1,73 @@ +--- +sidebar_label: setConfig() +title: setConfig() +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die Methode setConfig(). Lesen Sie Entwickleranleitungen und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# setConfig() + +### Beschreibung {#description} + +@short: Aktualisiert die aktuelle Konfiguration des Pivot-Widgets + +Die Methode wird verwendet, um die aktuelle Konfiguration des Pivot-Widgets zu aktualisieren. Sie ist nützlich, wenn der zugrunde liegende Datensatz des Widgets aktualisiert werden muss. Die Methode behält alle zuvor gesetzten Optionen bei, die im `setConfig`-Aufruf nicht explizit angegeben werden. + +### Verwendung {#usage} + +~~~jsx +setConfig(config: { [key:any]: any }): void; +~~~ + +### Parameter {#parameters} + +- `config` - (erforderlich) ein Objekt der Pivot-Konfiguration. Die vollständige Liste der Eigenschaften finden Sie [hier](api/overview/properties-overview.md) + +:::important +Die Methode ändert nur die Parameter, die Sie übergeben haben. Sie zerstört die aktuelle Komponente und initialisiert eine neue. +::: + +### Beispiel {#example} + +~~~jsx {21-41} +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// Konfigurationsparameter aktualisieren +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/de/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md new file mode 100644 index 0000000..7057bf3 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/setlocale-method.md @@ -0,0 +1,56 @@ +--- +sidebar_label: setLocale() +title: setLocale() +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek können Sie mehr über die Methode setLocale() erfahren. Entwicklerhandbücher und API-Referenz, Code-Beispiele und Live-Demos sowie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot. +--- + +# setLocale() + +### Beschreibung {#description} + +@short: Wendet eine neue Locale auf Pivot an + +### Verwendung {#usage} + +~~~jsx +setLocale(null | locale?: object): void; +~~~ + +### Parameter {#parameters} + +- `null` - (optional) setzt auf die Standard-Locale zurück (Englisch) +- `locale` - (optional) das Objekt mit den Daten der neuen Locale, die angewendet werden soll + +### Beispiel {#example} + +~~~jsx +// Pivot erstellen +const table = new pivot.Pivot("#root", { + fields, + data: dataset, + config: { + rows: ["studio", "genre"], + columns: [], + values: [ + { + field: "title", + method: "count" + }, + { + field: "score", + method: "max" + } + ] + } +}); + +// die Locale "de" auf Pivot anwenden +table.setLocale(pivot.locales.de); + +// die Standard-Locale auf Pivot anwenden +table.setLocale(); // oder setLocale(null); +~~~ + +**Verwandte Artikel**: +- [Lokalisierung](guides/localization.md) +- [`locale`](api/config/locale-property.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md new file mode 100644 index 0000000..7bce53e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/methods/showconfigpanel-method.md @@ -0,0 +1,55 @@ +--- +sidebar_label: showConfigPanel() +title: showConfigPanel() +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die Methode showConfigPanel(). Lesen Sie Entwicklerhandbücher und API-Referenz, testen Sie Code-Beispiele und Live-Demos und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# showConfigPanel() + +### Beschreibung {#description} + +@short: Zeigt das Konfigurationspanel an oder blendet es aus + +Diese Methode ist nützlich, wenn die Sichtbarkeit des Konfigurationspanels ohne Benutzerinteraktion gesteuert werden soll. Beispielsweise können Sie das Panel basierend auf einer anderen Interaktion oder einem anderen Zustand in Ihrer Anwendung ein- oder ausblenden. + +### Verwendung {#usage} + +~~~jsx +showConfigPanel({mode: boolean}): void; +~~~ + +### Parameter {#parameters} + +- `mode` (boolean) - (erforderlich) Wenn der Wert auf **true** gesetzt ist (Standard), wird das Konfigurationspanel angezeigt; bei **false** wird es ausgeblendet + +### Beispiel {#example} + +~~~jsx {21-23} +// Pivot erstellen +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 +}) +~~~ + +**Verwandte Artikel**: +- [Event `show-config-panel`](api/events/show-config-panel-event.md) +- [Eigenschaft `configPanel`](api/config/configpanel-property.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/overview/events-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/events-overview.md new file mode 100644 index 0000000..cf437a1 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/events-overview.md @@ -0,0 +1,19 @@ +--- +sidebar_label: Events-Übersicht +title: Events-Übersicht +description: Die Events-Übersicht von JavaScript Pivot finden Sie in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Events-Übersicht {#events-overview} + +| Name | Beschreibung | +| ------------------------------------------------- | ----------------------------------------------- | +| [](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/de/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md new file mode 100644 index 0000000..e28402e --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/internal-eventbus-overview.md @@ -0,0 +1,15 @@ +--- +sidebar_label: Event Bus-Methoden +title: Event Bus-Methoden +description: Sie finden eine Übersicht über die internen Event Bus-Methoden von JavaScript Pivot in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek. Erkunden 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. +--- + +# Übersicht der Event Bus-Methoden {#event-bus-methods-overview} + +| Name | Beschreibung | +| ---------------------------------------------- | ------------------------------------------------- | +| [](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/de/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md new file mode 100644 index 0000000..3c68e5c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/internal-state-overview.md @@ -0,0 +1,13 @@ +--- +sidebar_label: State-Methoden +title: State-Methoden +description: Sie finden eine Übersicht der internen State-Methoden von JavaScript Pivot in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# Übersicht der State-Methoden {#state-methods-overview} + +| Name | Beschreibung | +| ---------------------------------------------- | -------------------------------------------------- | +| [](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/de/docusaurus-plugin-content-docs/current/api/overview/main-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/main-overview.md new file mode 100644 index 0000000..2bc075f --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/main-overview.md @@ -0,0 +1,80 @@ +--- +sidebar_label: API-Übersicht +title: API-Übersicht +description: Eine API-Übersicht von JavaScript Pivot finden Sie in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek. Durchsuchen Sie Entwicklerhandbücher und die API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# API-Übersicht {#api-overview} + +## Pivot-Konstruktor {#pivot-constructor} + +~~~jsx +new pivot.Pivot("#root", { + // Konfigurationsparameter +}); +~~~ + +**Parameter**: + +- ein HTML-Container (die ID des HTML-Containers) +- ein Objekt der Konfigurationsparameter ([hier prüfen](#pivot-properties)) + +## Pivot-Methoden {#pivot-methods} + +| Name | Beschreibung | +| ------------------------------------------- | ------------------------------------------ | +| [](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) | + +## Interne Pivot-API {#pivot-internal-api} + +### Event-Bus-Methoden {#event-bus-methods} + +| Name | Beschreibung | +| :------------------------------------ | :------------------------------------------- | +| [](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-Methoden {#state-methods} + +| Name | Beschreibung | +| :---------------------------------------------- | :------------------------------------------------- | +| [](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 {#pivot-events} + +| Name | Beschreibung | +| :------------------------------------------------ | :---------------------------------------------- | +| [](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-Eigenschaften {#pivot-properties} + +| Name | Beschreibung | +| :------------------------------------------------- | :----------------------------------------------- | +| [](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/de/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md new file mode 100644 index 0000000..0158652 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/methods-overview.md @@ -0,0 +1,14 @@ +--- +sidebar_label: Methodenübersicht +title: Methodenübersicht +description: Die Methodenübersicht von JavaScript Pivot finden Sie in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek. Lesen 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. +--- + +# Methodenübersicht {#methods-overview} + +| Name | Beschreibung | +| ------------------------------------------- | ----------------------------------------------- | +| [](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/de/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md new file mode 100644 index 0000000..11a3550 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/properties-overview.md @@ -0,0 +1,24 @@ +--- +sidebar_label: Eigenschaften-Übersicht +title: Eigenschaften-Übersicht +description: Sie finden die Eigenschaften-Übersicht von JavaScript Pivot in der Dokumentation der DHTMLX JavaScript Pivot Bibliothek. 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. +--- + +# Eigenschaften-Übersicht {#properties-overview} + +Informationen zur Konfiguration von **Pivot** finden Sie im Abschnitt [Konfiguration](guides/configuration.md). + +| Name | Beschreibung | +| -------------------------------------------------- | ------------------------------------------------ | +| [](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/de/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md new file mode 100644 index 0000000..214809d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/overview/table-events-overview.md @@ -0,0 +1,16 @@ +--- +sidebar_label: Übersicht der Table-Events +title: Übersicht der Table-Events +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek finden Sie eine Übersicht der Table-Events von JavaScript Pivot. Durchsuchen Sie Entwicklerleitfäden und API-Referenzen, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# Übersicht der Table-Events {#table-events-overview} + +Die Methode [`getTable`](api/methods/gettable-method.md) der Pivot-API ermöglicht den Zugriff auf die zugrunde liegende Table-Widget-Instanz innerhalb von Pivot und die Ausführung der folgenden Table-Events: + +| Name | Beschreibung | +| ------------------------------------------------- | ----------------------------------------------- | +| [](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/de/docusaurus-plugin-content-docs/current/api/table/close-row.md b/i18n/de/docusaurus-plugin-content-docs/current/api/table/close-row.md new file mode 100644 index 0000000..be08ae2 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/table/close-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: close-row +title: close-row +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das close-row-Event. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter +--- + +# close-row + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn eine Zeile geschlossen (eingeklappt) wird + +Um das Table-Event auszulösen, muss über die Methode [`getTable`](api/methods/gettable-method.md) auf die zugrunde liegende Table-Widget-Instanz innerhalb von Pivot zugegriffen werden. Der Baumstruktur-Modus muss über die Eigenschaft [`tableShape`](api/config/tableshape-property.md) aktiviert sein. + +### Verwendung {#usage} + +```jsx {} +"close-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### Parameter {#parameters} + +Der Callback der Aktion nimmt ein Objekt mit den folgenden Parametern entgegen: + +- `id` - (erforderlich) die ID einer Zeile, die verschachtelte Zeilen enthält +- `nested` - (optional) wenn auf **true** gesetzt, werden alle verschachtelten Elemente eingeklappt + +:::note +Wenn `id` auf 0 und `nested` auf **true** gesetzt wird, werden alle Zeilen in der Tabelle eingeklappt +::: + +### Beispiel {#example} + +Der folgende Ausschnitt zeigt, wie alle Zeilen per Schaltflächenklick geöffnet bzw. geschlossen werden: + + + +**Verwandte Artikel**: +- [`getTable`](api/methods/gettable-method.md) +- [Alle Zeilen auf- und zuklappen](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/table/export.md b/i18n/de/docusaurus-plugin-content-docs/current/api/table/export.md new file mode 100644 index 0000000..4dec2d8 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/table/export.md @@ -0,0 +1,109 @@ +--- +sidebar_label: export +title: export +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das export-Event. Lesen 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 +--- + +# export + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn Daten exportiert werden + +Um das Table-Event auszulösen, muss auf die Table-Instanz innerhalb von Pivot über die Methode [`getTable`](api/methods/gettable-method.md) zugegriffen werden. + +### Verwendung {#usage} + +```jsx +"export": ({ + options: { + format: "csv" | "xlsx", + fileName?: string, + header?: boolean, + footer?: boolean, + download?: boolean, + + /* XLSX-Einstellungen*/ + styles?: boolean | { + header?: { + fontWeight?: "bold", + color?: string, + background?: string, + align?: "left"|"right"|"center", + borderBottom?: string, + borderRight?: string, + } + lastHeaderCell?: { /* wie header */ }, + cell?: { /* wie header */ }; + firstFooterCell?: { /* wie header */ }, + footer?: {/* wie 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-Einstellungen */ + rows: string, + cols: string, + }, + result?: any, +}) => boolean|void; +``` + +Die `export`-Aktion des Table-Widgets verfügt über folgende Parameter, die Sie nach Bedarf konfigurieren können: + +- `options` - ein Objekt mit den Export-Optionen; die Optionen unterscheiden sich je nach Formattyp +- `result` - das Ergebnis der exportierten Excel- oder CSV-Daten (in der Regel ein Blob oder eine Datei, abhängig von der Option `download`) + + **Gemeinsame Optionen für beide Formate ("csv" und "xlsx")**: + + - `format` (string) - (optional) das Exportformat, das "csv" oder "xlsx" sein kann + - `fileName` (string) - (optional) ein Dateiname (standardmäßig "data") + - `header` (boolean) - (optional) legt fest, ob eine Kopfzeile exportiert werden soll (standardmäßig **true**) + - `footer` (boolean) - (optional) legt fest, ob eine Fußzeile exportiert werden soll (standardmäßig **true**) + - `download` (boolean) - (optional) legt fest, ob eine Datei heruntergeladen werden soll. Standardmäßig ist **true** gesetzt. Wenn auf **false** gesetzt, wird die Datei nicht heruntergeladen; Excel- oder CSV-Daten (Blob) sind dann als `ev.result` verfügbar + + **Optionen spezifisch für das "xlsx"-Format**: + + - `sheetName` (string) - der Name des Excel-Tabellenblatts (standardmäßig "data") + - `styles` (boolean oder Objekt) - wenn auf **false** gesetzt, wird das Grid ohne jegliche Formatierung exportiert; kann über eine Menge von Style-Eigenschaften konfiguriert werden: + - `header` - ein Objekt mit den folgenden Einstellungen für Kopfzeilenzellen: + - `fontWeight` (string) - (optional) kann auf "bold" gesetzt werden; andernfalls wird die Schrift normal dargestellt + - `color` (string) - (optional) Textfarbe in der Kopfzeile + - `background` (string) - (optional) Hintergrundfarbe für die Kopfzeile + - `align` - (optional) Textausrichtung, die "left"|"right"|"center" sein kann. Wenn nicht gesetzt, wird die in Excel festgelegte Ausrichtung verwendet + - `borderBottom` (string) - (optional) der Stil des unteren Rahmens + - `borderRight` (string) - (optional) der Stil des rechten Rahmens (z. B. *borderRight: "0.5px solid #dfdfdf"*) + - `lastHeaderCell` - Style-Eigenschaften für die letzte Zeile der Kopfzeilenzellen. Die Eigenschaften sind dieselben wie für *header* + - `cell` - Style-Eigenschaften für Datenzellen. Die Eigenschaften sind dieselben wie für *header* + - `firstFooterCell` - Style-Eigenschaften für die erste Zeile der Fußzeilenzellen. Die Eigenschaften sind dieselben wie für *header* + - `footer` - Style-Eigenschaften für Fußzeilenzellen. Die Eigenschaften sind dieselben wie für *header* + - `cellTemplate` - eine Funktion zur Anpassung des Exportwerts jeder Zelle. Sie erhält den Wert, das Zeilen- und das Spaltenobjekt als Parameter und gibt den benutzerdefinierten Wert für den Export zurück + - `headerCellTemplate` - eine Funktion, die den Wert einer Kopf- oder Fußzeilenzelle beim Export anpasst. Sie wird mit dem Text, dem Kopfzeilenzell-Objekt, dem Spaltenobjekt und dem Zellentyp ("header" oder "footer") aufgerufen. Dadurch können die exportierten Kopf-/Fußzeilenwerte geändert werden + - `cellStyle` - eine Funktion, die die Formatierung einzelner Zellen beim Export anpasst. Sie erhält den Wert, das Zeilen- und das Spaltenobjekt als Parameter und sollte ein Objekt mit Style-Eigenschaften zurückgeben (z. B. Ausrichtung oder Format) + - `headerCellStyle` - ähnlich wie cellStyle, aber speziell für Kopf- und Fußzeilenzellen. Diese Funktion erhält den Text, das Kopfzeilenzell-Objekt, das Spaltenobjekt und den Typ ("header" oder "footer") und gibt Style-Eigenschaften zurück + :::note + Standardmäßig werden beim "xlsx"-Format Datums- und Zahlenfelder als Rohwerte mit dem Standardformat oder dem über die Eigenschaft [`fields`](api/config/fields-property.md) definierten Format exportiert. Ist jedoch eine Vorlage für ein Feld definiert (siehe Eigenschaft [`tableShape`](api/config/tableshape-property.md)), wird der durch diese Vorlage gerenderte Wert exportiert. Wenn sowohl eine Vorlage als auch `format` gesetzt sind, überschreiben die Vorlageneinstellungen die Formateinstellungen. + ::: + + **Optionen spezifisch für das "csv"-Format**: + + - `rows` (string) - (optional) Zeilentrennzeichen, standardmäßig "\n" + - `cols` (string) - (optional) Spaltentrennzeichen, standardmäßig "\t" + +## Beispiel {#example} + +In diesem Snippet sehen Sie, wie Daten exportiert werden: + + + +**Verwandte Artikel**: +- [`getTable`](api/methods/gettable-method.md) +- [Daten exportieren](guides/exporting-data.md) +- [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/table/filter-rows.md b/i18n/de/docusaurus-plugin-content-docs/current/api/table/filter-rows.md new file mode 100644 index 0000000..bd58784 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/table/filter-rows.md @@ -0,0 +1,35 @@ +--- +sidebar_label: filter-rows +title: filter-rows +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das filter-rows-Event. Lesen Sie Entwickleranleitungen und die API-Referenz, testen Sie Code-Beispiele und Live-Demos, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter +--- + +# filter-rows + +### Beschreibung {#description} + +@short: Wird beim Filtern von Daten ausgelöst + +Um das Table-Event auszulösen, ist es erforderlich, über die Methode [`getTable`](api/methods/gettable-method.md) auf die Table-Instanz innerhalb von Pivot zuzugreifen. + +### Verwendung {#usage} + +```jsx {} +"filter-rows": ({ + filter?: any +}) => boolean|void; +``` + +### Parameter {#parameters} + +Der Callback der Aktion nimmt ein Objekt mit den folgenden Parametern entgegen: + +- `filter` - (optional) eine beliebige Filterfunktion, die jedes Element aus dem Daten-Array entgegennimmt und für jedes Element **true** oder **false** zurückgibt + +### Beispiel {#example} + +Der folgende Ausschnitt zeigt, wie aggregierte (sichtbare) Daten im Tabellenkörper anhand eines Eingabewerts gefiltert werden: + + + +**Verwandter Artikel**: [`getTable`](api/methods/gettable-method.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/api/table/open-row.md b/i18n/de/docusaurus-plugin-content-docs/current/api/table/open-row.md new file mode 100644 index 0000000..aa4a991 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/api/table/open-row.md @@ -0,0 +1,43 @@ +--- +sidebar_label: open-row +title: open-row +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über das open-row-Event. Sehen Sie sich Entwicklerhandbücher und API-Referenzen an, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter +--- + +# open-row + +### Beschreibung {#description} + +@short: Wird ausgelöst, wenn eine Zeile geöffnet (aufgeklappt) wird + +Um das Table-Event auszulösen, muss über die Methode [`getTable`](api/methods/gettable-method.md) auf die Table-Instanz innerhalb von Pivot zugegriffen werden. Der Baumstruktur-Modus muss über die Eigenschaft [`tableShape`](api/config/tableshape-property.md) aktiviert sein. + +### Verwendung {#usage} + +```jsx {} +"open-row": ({ + id: string | number, + nested?: boolean +}) => boolean|void; +``` + +### Parameter {#parameters} + +Der Callback der Aktion erhält ein Objekt mit den folgenden Parametern: + +- `id` - (erforderlich) die ID einer Zeile, die verschachtelte Zeilen enthält +- `nested` - (optional) wenn auf **true** gesetzt, werden alle verschachtelten Einträge aufgeklappt + +:::note +Wenn `id` auf 0 und `nested` auf **true** gesetzt ist, werden alle Zeilen in der Tabelle aufgeklappt +::: + +### Beispiel {#example} + +Der folgende Code-Ausschnitt zeigt, wie alle Zeilen per Klick auf eine Schaltfläche geöffnet/geschlossen werden können: + + + +**Verwandte Artikel**: +- [`getTable`](api/methods/gettable-method.md) +- [Alle Zeilen auf-/zuklappen](guides/configuration.md#expandingcollapsing-all-rows) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/add_remove.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/add_remove.png new file mode 100644 index 0000000..81dcb52 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/add_remove.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/apply_filter.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/apply_filter.png new file mode 100644 index 0000000..53905a7 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/apply_filter.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/config_panel.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/config_panel.png new file mode 100644 index 0000000..41b7568 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/config_panel.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/filter.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/filter.png new file mode 100644 index 0000000..b4b1599 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/filter.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/filter_applied.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/filter_applied.png new file mode 100644 index 0000000..9ed7479 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/filter_applied.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/operations.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/operations.png new file mode 100644 index 0000000..80f6f79 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/operations.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/pivot-main.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/pivot-main.png new file mode 100644 index 0000000..5eaa953 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/pivot-main.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/priority.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/priority.png new file mode 100644 index 0000000..a827e01 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/priority.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/table.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/table.png new file mode 100644 index 0000000..f0fb3a9 Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/table.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/assets/trial_pivot.png b/i18n/de/docusaurus-plugin-content-docs/current/assets/trial_pivot.png new file mode 100644 index 0000000..f2e21cf Binary files /dev/null and b/i18n/de/docusaurus-plugin-content-docs/current/assets/trial_pivot.png differ diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/configuration.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/configuration.md new file mode 100644 index 0000000..440ed9c --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/configuration.md @@ -0,0 +1,740 @@ +--- +sidebar_label: Konfiguration +title: Konfiguration +description: Sie können mehr über die Konfiguration in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren. Entdecken 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. +--- + +# Konfiguration {#configuration} + +Konfigurieren Sie die Pivot-Tabelle und das Konfigurationspanel über die folgende API: + +- [`config`](api/config/config-property.md) — definiert die Struktur der Pivot-Tabelle und wie Daten aggregiert werden +- [`render-table`](api/events/render-table-event.md) — ändert die Tabellenkonfiguration zur Laufzeit +- [`tableShape`](api/config/tableshape-property.md) — konfiguriert das Erscheinungsbild der Pivot-Tabelle +- [`columnShape`](api/config/columnshape-property.md) — konfiguriert das Erscheinungsbild und Verhalten von Spalten +- [`headerShape`](api/config/headershape-property.md) — konfiguriert das Erscheinungsbild und Verhalten von Kopfzeilen +- [`configPanel`](api/config/configpanel-property.md) — steuert die Sichtbarkeit des Konfigurationspanels +- [`setLocale`](api/methods/setlocale-method.md) — wendet ein Locale an (siehe [Lokalisierung](guides/localization.md)) +- [`data`](api/config/data-property.md), [`fields`](api/config/fields-property.md) — lädt Daten und Feld-Metadaten +- [`predicates`](api/config/predicates-property.md) — verarbeitet Daten vor der Aggregation +- [`methods`](api/config/methods-property.md) — definiert benutzerdefinierte Aggregationsmethoden +- [`limits`](api/config/limits-property.md) — begrenzt die Anzahl der Zeilen und Spalten im finalen Datensatz + +Anweisungen zur Arbeit mit Daten finden Sie unter [Mit Daten arbeiten](guides/working-with-data.md). + +Sie können die folgenden Elemente der Pivot-Tabelle konfigurieren: + +- Spalten und Zeilen +- Kopf- und Fußzeilen +- Zellen +- Tabellengrößen + +## Tabelle skalieren {#resizing-the-table} + +Verwenden Sie die Eigenschaft [`tableShape`](api/config/tableshape-property.md), um die Größe von Zeilen, Spalten, Kopf- und Fußzeile zu ändern. + +Das folgende Code-Snippet zeigt die Standardgrößen: + +~~~jsx +const sizes = { + rowHeight: 34, + headerHeight: 30, + footerHeight: 30, + columnWidth: 150 +}; +~~~ + +Das folgende Code-Snippet überschreibt die Standardgrößen: + +~~~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 +Um die Breite bestimmter Spalten festzulegen, verwenden Sie den Parameter `width` der Eigenschaft [`columnShape`](api/config/columnshape-property.md). +::: + +## Spalten automatisch an den Inhalt anpassen {#autosize-columns-to-content} + +Verwenden Sie den Parameter `autoWidth` der Eigenschaft [`columnShape`](api/config/columnshape-property.md), um Spaltenbreiten automatisch zu berechnen. Alle `autoWidth`-Unterparameter sind optional — vollständige Beschreibungen finden Sie in der Referenz zu [`columnShape`](api/config/columnshape-property.md). + +Das `autoWidth`-Objekt akzeptiert die folgenden Parameter: + +- `columns` — Objekt, das festlegt, welche Felder eine automatisch berechnete Breite erhalten +- `auto` — passt die Breite an die Kopfzeile, den Zelleninhalt oder beides an +- `maxRows` — Anzahl der analysierten Datenzeilen zur Ermittlung der Spaltengröße (Standard: 20) +- `firstOnly` — wenn `true` (Standard), wird jedes Feld nur einmal analysiert. Wenn mehrere Spalten auf demselben Feld basieren (z. B. `oil` mit `count` und `oil` mit `sum`), wird nur die erste Spalte analysiert und die anderen übernehmen deren Breite + +Das folgende Code-Snippet aktiviert `autoWidth` für vier Felder und deaktiviert `firstOnly`, sodass jede Spalte eine eigene Messung erhält: + +~~~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: { + // Spaltenbreite für diese Felder berechnen + columns: { + studio: true, + genre: true, + title: true, + score: true + }, + // alle Felder analysieren + firstOnly: false + } + } +}); +~~~ + +## Templates auf Zellen anwenden {#applying-templates-to-cells} + +### Templates über tableShape hinzufügen {#add-templates-via-tableshape} + +Verwenden Sie den Parameter `templates` der Eigenschaft [`tableShape`](api/config/tableshape-property.md), um Zellwerte über eine Funktion zu rendern. Jeder Schlüssel ist eine Feld-ID und jeder Wert ist eine Funktion, die einen String zurückgibt. Alle Spalten, die auf dem angegebenen Feld basieren, erhalten das Template. + +Das folgende Beispiel wendet ein Template auf `state`-Zellen an, das den kombinierten Namen eines Bundesstaates anzeigt (vollständiger Name plus Abkürzung): + +~~~jsx {10-15} +const states = { + "California": "CA", + "Colorado": "CO", + "Connecticut": "CT", + "Florida": "FL", + // weitere Werte +}; + +const table = new pivot.Pivot("#root", { + tableShape: { + templates: { + // Werte der "state"-Zellen anpassen + state: v => v + ` (${states[v]})`, + } + }, + fields, + data, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // weitere Werte + ], + }, + fields, +}); +~~~ + +### Template über den template-Helper hinzufügen {#adding-a-template-via-the-template-helper} + +Um HTML-Inhalte in Body-Zellen einzufügen, verwenden Sie den Helper [`pivot.template`](api/helpers/template.md) und weisen Sie das Ergebnis der Eigenschaft `cell` des Spaltenobjekts zu. Wenden Sie das Template unmittelbar vor dem Rendern der Tabelle an, indem Sie das Ereignis [`render-table`](api/events/render-table-event.md) mit der Methode [`api.intercept`](api/internal/intercept-method.md) abfangen. + +Das folgende Beispiel fügt Icons (Stern oder Flagge) in Body-Zellen ein, basierend auf dem Feld (`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") { + // Template auf Spaltenzellen aus dem "rows"-Bereich anwenden + c.cell = pivot.template(({ value, method, row, column }) => cellTemplate(value, method, row, column)); + } + return c; + }); +}); +~~~ + +## Templates auf Kopfzeilen anwenden {#applying-templates-to-headers} + +### Templates über headerShape hinzufügen {#add-templates-via-headershape} + +Um das Textformat in Kopfzeilen zu steuern, verwenden Sie den Parameter `template` der Eigenschaft [`headerShape`](api/config/headershape-property.md). Der Parameter ist eine Funktion, die: + +- das Feld-Label, die ID und das Sublabel (den Methodennamen, falls vorhanden) entgegennimmt +- den verarbeiteten Wert zurückgibt + +Das Standard-Template lautet: + +~~~js +template: (label, id, subLabel) => + label + (subLabel ? ` (${subLabel})` : "") +~~~ + +Ohne ein benutzerdefiniertes Template zeigen Felder im `values`-Bereich das Label und die Methode an (z. B. `Oil(count)`), und Felder in anderen Bereichen zeigen den `label`-Wert an. Ein [`predicates`](api/config/predicates-property.md)-Template überschreibt das `headerShape`-Template. + +Das folgende Beispiel konvertiert den Kopfzeilentext in Kleinbuchstaben und erzeugt Labels wie `profit (sum)`: + +~~~jsx {3-6} +new pivot.Pivot("#pivot", { + data, + headerShape: { + // benutzerdefiniertes Template für den Kopfzeilentext + template: (label, id, subLabel) => (label + (subLabel ? ` (${subLabel})` : "")).toLowerCase(), + }, + config: { + rows: ["state", "product_type"], + columns: [], + values: [ + { + field: "profit", + method: "sum" + }, + { + field: "sales", + method: "sum" + }, + // weitere Werte + ], + }, + fields, +}); +~~~ + +### Templates über den template-Helper hinzufügen {#add-templates-via-the-template-helper} + +Um HTML-Inhalte in Kopfzeilenzellen einzufügen, verwenden Sie den Helper [`pivot.template`](api/helpers/template.md) und weisen Sie das Ergebnis der Eigenschaft `cell` des Kopfzeilenzellobjekts zu. Wenden Sie das Template unmittelbar vor dem Rendern der Tabelle an, indem Sie das Ereignis [`render-table`](api/events/render-table-event.md) mit der Methode [`api.intercept`](api/internal/intercept-method.md) abfangen. + +Das folgende Beispiel fügt Icons hinzu in: + +- Kopfzeilen-Labels basierend auf dem Feldnamen (zum Beispiel erhält `id` ein Globus-Icon) +- Spaltenüberschriften basierend auf dem Zellenwert (farbige Pfeil-Indikatoren basierend auf dem `status`-Wert) + +~~~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") { + // Template auf die erste Kopfzeile der Spalten aus dem "rows"-Bereich anwenden + c.header[0].cell = pivot.template(({ value, field }) => rowsHeaderTemplate(value, field)); + } else { + // Kopfzeilenzellen, die Werte aus dem "status"-Feld anzeigen + const headerCell = c.header.find((h) => h.field === "status"); + if (headerCell) { + headerCell.cell = pivot.template(({ value }) => statusTemplate(value)); + } + } + return c; + }); +}); +~~~ + +## Spalten einklappbar machen {#make-columns-collapsible} + +Um Benutzern zu ermöglichen, Spalten unter einer gemeinsamen Kopfzeile ein- und auszuklappen, setzen Sie den Parameter `collapsible` der Eigenschaft [`headerShape`](api/config/headershape-property.md) auf `true`. + +Das folgende Code-Snippet aktiviert einklappbare Spaltenüberschriften: + +~~~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" + } + ] + } +}); +~~~ + +## Spalten fixieren {#freezing-columns} + +Fixieren Sie Spalten links oder rechts, damit sie sichtbar bleiben, während der Rest der Tabelle gescrollt wird. Verwenden Sie den Parameter `split` der Eigenschaft [`tableShape`](api/config/tableshape-property.md) und setzen Sie `left` oder `right` auf `true`. + +### Spalten links fixieren {#freeze-columns-on-the-left} + +Wenn `split.left` `true` ist, entspricht die Anzahl der fixierten Spalten der Anzahl der `rows`-Felder in der Eigenschaft [`config`](api/config/config-property.md). Im Baumstruktur-Modus wird unabhängig von der Anzahl der `rows`-Felder nur eine Spalte fixiert. + +Das folgende Code-Snippet fixiert eine Spalte links (ein `rows`-Feld ist definiert): + +~~~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 } + } +}); +~~~ + +Um eine benutzerdefinierte Anzahl von fixierten Spalten festzulegen, hören Sie auf das Ereignis [`render-table`](api/events/render-table-event.md) und überschreiben Sie `tableConfig.split`. Vermeiden Sie das Aufteilen von Spalten mit Colspans. + +Das folgende Code-Snippet fixiert alle `rows`-Spalten plus doppelt so viele `values`-Felder links: + +~~~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 + }; +}); +~~~ + +### Spalten rechts fixieren {#freezing-columns-on-the-right} + +Setzen Sie `split.right` auf `true`, um Gesamtsummen-Spalten rechts zu fixieren. + +Das folgende Code-Snippet fixiert die Gesamtsummen-Spalte rechts: + +~~~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" + } + ] + } +}); +~~~ + +Um eine benutzerdefinierte Anzahl von Spalten rechts zu fixieren, hören Sie auf das Ereignis [`render-table`](api/events/render-table-event.md) und überschreiben Sie `tableConfig.split`. Vermeiden Sie das Aufteilen von Spalten mit Colspans. + +Das folgende Code-Snippet fixiert so viele Spalten rechts wie es `values`-Felder gibt: + +~~~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, + } +}) +~~~ + +## In Spalten sortieren {#sort-in-columns} + +Die Sortierung in der Benutzeroberfläche ist standardmäßig aktiviert — Benutzer klicken auf eine Spaltenüberschrift, um zu sortieren. Um sie zu deaktivieren, setzen Sie den Parameter `sort` der Eigenschaft [`columnShape`](api/config/columnshape-property.md) auf `false`. + +Das folgende Code-Snippet 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 + } +}); +~~~ + +Weitere Informationen zur Standard-Sortierung, benutzerdefinierten Komparatoren und Laufzeit-Updates finden Sie unter [Daten sortieren](guides/working-with-data.md#sorting-data). + +## Baumstruktur-Modus aktivieren {#enabling-the-tree-mode} + +Der Baumstruktur-Modus stellt Daten hierarchisch mit ausklappbaren Zeilen dar. Setzen Sie den Parameter `tree` der Eigenschaft [`tableShape`](api/config/tableshape-property.md) auf `true` (Standard: `false`). Das erste Feld des `rows`-Arrays in [`config`](api/config/config-property.md) wird zur übergeordneten Zeile. + +Das folgende Code-Snippet aktiviert den Baumstruktur-Modus mit `studio` als übergeordneter und `genre` als untergeordneten Zeilen: + +~~~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" + } + ] + } +}); +~~~ + +## Alle Zeilen aus- oder einklappen {#expandingcollapsing-all-rows} + +Um alle Zeilen programmatisch aus- oder einzuklappen, aktivieren Sie den Baumstruktur-Modus über die Eigenschaft [`tableShape`](api/config/tableshape-property.md). Greifen Sie dann mit der Methode [`getTable`](api/methods/gettable-method.md) auf die Table-Widget-Instanz zu und lösen Sie das Ereignis [`open-row`](api/table/open-row.md) oder [`close-row`](api/table/close-row.md) über die Methode `api.exec` der Tabelle aus. + +Das folgende Beispiel rendert die Schaltflächen "Alle öffnen" und "Alle schließen", die im Baumstruktur-Modus jeden Ast aus- oder einklappen: + +~~~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(); +// alle Tabellenäste beim Rendern geschlossen halten +api.intercept("render-table", (ev) => { + ev.config.data.forEach((r) => (r.open = false)); + + // hier false zurückgeben, um das Rendern der Tabelle zu verhindern + // 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); +~~~ + +## Ausrichtung des Kopfzeilentexts ändern {#change-header-text-orientation} + +Um den Kopfzeilentext von horizontal auf vertikal zu drehen, setzen Sie den Parameter `vertical` der Eigenschaft [`headerShape`](api/config/headershape-property.md) auf `true`. + +Das folgende Code-Snippet rendert vertikalen Kopfzeilentext: + +~~~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" + } + ] + } +}); +~~~ + +## Sichtbarkeit des Konfigurationspanels steuern {#controlling-visibility-of-configuration-panel} + +Das Konfigurationspanel wird standardmäßig angezeigt. Benutzer können es über die Schaltfläche **Einstellungen ausblenden** / **Einstellungen anzeigen** umschalten. Steuern Sie das Panel programmatisch über die Eigenschaft [`configPanel`](api/config/configpanel-property.md), das Ereignis [`show-config-panel`](api/events/show-config-panel-event.md) oder die Methode [`showConfigPanel`](api/methods/showconfigpanel-method.md). + +### Konfigurationspanel ausblenden {#hide-the-configuration-panel} + +Um das Panel bei der Initialisierung auszublenden, setzen Sie die Eigenschaft [`configPanel`](api/config/configpanel-property.md) auf `false`. + +Das folgende Code-Snippet initialisiert Pivot mit ausgeblendetem Panel: + +~~~jsx +// das Konfigurationspanel ist beim Start ausgeblendet +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" + } + ] + } +}); +~~~ + +Um das Panel zur Laufzeit umzuschalten, lösen Sie das Ereignis [`show-config-panel`](api/events/show-config-panel-event.md) mit der Methode [`api.exec`](api/internal/exec-method.md) aus und setzen Sie den Parameter `mode` auf `false`. + +Das folgende Code-Snippet blendet das Panel nach der Initialisierung aus: + +~~~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" + } + ] + } +}); +// Konfigurationspanel ausblenden +table.api.exec("show-config-panel", { + mode: false +}); +~~~ + +### Standard-Umschalten deaktivieren {#disable-the-default-toggling} + +Um die Standard-Umschalttaste vollständig zu blockieren, fangen Sie das Ereignis [`show-config-panel`](api/events/show-config-panel-event.md) mit der Methode [`api.intercept`](api/internal/intercept-method.md) ab und geben Sie `false` zurück. + +Das folgende Code-Snippet deaktiviert die Umschalttaste: + +~~~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; +}); +~~~ + +Als alternative API verwenden Sie die Methode [`showConfigPanel`](api/methods/showconfigpanel-method.md). + +### Aktionen mit Feldern im Panel {#actions-with-fields-in-the-panel} + +Das Konfigurationspanel unterstützt die folgenden Feldoperationen: + +- [`add-field`](api/events/add-field-event.md) — ein Feld zu einem Bereich hinzufügen +- [`delete-field`](api/events/delete-field-event.md) — ein Feld aus einem Bereich entfernen +- [`update-field`](api/events/update-field-event.md) — die Methode oder Einstellungen eines Feldes aktualisieren +- [`move-field`](api/events/move-field-event.md) — Felder innerhalb eines Bereichs neu anordnen + +**Verwandte Beispiele**: +- [Pivot 2. Texttemplates für Tabellen- und Kopfzeilenzellen hinzufügen](https://snippet.dhtmlx.com/n9ylp6b2) +- [Pivot 2. Benutzerdefinierte fixierte Spalten (eigene Anzahl)](https://snippet.dhtmlx.com/53erlmgp) +- [Pivot 2. Alle Zeilen aus- und einklappen](https://snippet.dhtmlx.com/i4mi6ejn) +- [Pivot 2. Fixierte Spalten links und rechts](https://snippet.dhtmlx.com/lahf729o) +- [Pivot 2. Sortierung](https://snippet.dhtmlx.com/j7vtief6) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/exporting-data.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/exporting-data.md new file mode 100644 index 0000000..a557756 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/exporting-data.md @@ -0,0 +1,45 @@ +--- +sidebar_label: Daten exportieren +title: Daten exportieren +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie, wie Sie Daten exportieren. Lesen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Daten exportieren {#exporting-data} + +Pivot exportiert Tabellendaten im XLSX- oder CSV-Format über das zugrunde liegende Table-Widget. Greifen Sie mit der Methode [`getTable`](api/methods/gettable-method.md) auf die Table-Instanz zu und lösen Sie dann das [`export`](api/table/export.md)-Event mit der Methode [`api.exec`](api/internal/exec-method.md) der Table aus. + +Das folgende Beispiel greift auf die Table-Instanz zu und löst das `export`-Event im CSV- und XLSX-Format aus: + +~~~jsx +const widget = new pivot.Pivot("#root", { /* Einstellungen */ }); + +widget.getTable().exec("export", { + options: { + format: "csv", + cols: ";" + } +}); + +widget.getTable().exec("export", { + options: { + format: "xlsx", + fileName: "My Report", + sheetName: "Quarter 1" + } +}); +~~~ + +:::tip +Die Methode [`getTable`](api/methods/gettable-method.md) akzeptiert einen optionalen booleschen Parameter `wait`. Übergeben Sie `true`, um ein Promise zu erhalten, das aufgelöst wird, sobald die Table-API verfügbar ist. Nützlich, wenn die Table-API bereits während der Pivot-Initialisierung bereit sein muss. +::: + +## Beispiel {#example} + +Der folgende Ausschnitt exportiert Daten: + + + +**Verwandte Artikel**: + +- [Datumsformatierung](guides/localization.md#date-formatting) +- [`export`](api/table/export.md) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/initialization.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/initialization.md new file mode 100644 index 0000000..95a3e7f --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/initialization.md @@ -0,0 +1,86 @@ +--- +sidebar_label: Initialisierung +title: Initialisierung +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie alles über die Initialisierung. Durchsuchen Sie Entwicklerhandbücher und die API-Referenz, testen Sie Code-Beispiele und Live-Demos, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Initialisierung {#initialization} + +Diese Anleitung erklärt, wie Sie Pivot auf einer Seite erstellen und Ihre Anwendung mit Pivot-Tabellenfunktionen erweitern. Führen Sie die folgenden Schritte aus, um eine einsatzbereite Komponente zu erhalten: + +1. [Binden Sie die Pivot-Quelldateien auf der Seite ein](#include-source-files). +2. [Erstellen Sie einen Container für Pivot](#create-a-container). +3. [Initialisieren Sie Pivot mit einem Konstruktor](#initialize-pivot). + +## Quelldateien einbinden {#include-source-files} + +Eine Pivot-App benötigt zwei Quelldateien auf der Seite. Anweisungen zum Herunterladen des Pakets finden Sie unter [Pakete herunterladen](how-to-start.md#step-1-downloading-and-installing-packages). + +Binden Sie die folgenden Dateien ein: + +- *pivot.js* +- *pivot.css* + +Legen Sie die korrekten relativen Pfade zu den Quelldateien fest: + +~~~html title="index.html" + + +~~~ + +## Container erstellen {#create-a-container} + +Pivot wird in ein HTML-Container-Element gerendert. Fügen Sie einen Container hinzu und weisen Sie ihm eine ID zu, zum Beispiel *"root"*: + +~~~html title="index.html" +
+~~~ + +## Pivot initialisieren {#initialize-pivot} + +Der Konstruktor `pivot.Pivot` akzeptiert zwei Parameter: + +- die ID des HTML-Containers +- ein Objekt mit Konfigurationseigenschaften + +Der folgende Code-Ausschnitt erstellt eine Pivot-Instanz im Container *"root"* mit initialen Feldern, Daten und Struktur: + +~~~jsx +// Pivot erstellen +const table = new pivot.Pivot("#root", { + // Konfigurationseigenschaften + fields, + data, + config: { + rows: ["studio", "genre"], + columns: ["title"], + values: [ + { + field: "score", + method: "max" + } + ] + } +}); +~~~ + +Der Konstruktor gibt eine Pivot-Instanz zurück. Rufen Sie API-Methoden auf der zurückgegebenen Instanz auf: + +- [`getTable`](api/methods/gettable-method.md) — Zugriff auf die zugrunde liegende Table-Widget-Instanz erhalten +- [`setConfig`](api/methods/setconfig-method.md) — die aktuelle Pivot-Konfiguration aktualisieren +- [`setLocale`](api/methods/setlocale-method.md) — eine neue Locale auf Pivot anwenden +- [`showConfigPanel`](api/methods/showconfigpanel-method.md) — das Konfigurationspanel ein- oder ausblenden + +## Konfigurationseigenschaften {#configuration-properties} + +Der Pivot-Konstruktor akzeptiert ein Objekt mit Konfigurationseigenschaften, die Daten, Layout und Verhalten steuern. + +:::info +Die vollständige Liste der Eigenschaften zur Konfiguration von Pivot finden Sie unter [Eigenschaften-Übersicht](api/overview/properties-overview.md). +::: + +## Beispiel {#example} + +Der folgende Ausschnitt initialisiert Pivot mit den initialen Daten: + + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md new file mode 100644 index 0000000..5ec5a5b --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-angular.md @@ -0,0 +1,325 @@ +--- +sidebar_label: Integration mit Angular +title: Integration mit Angular +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie, wie die Integration mit Angular funktioniert. Durchsuchen Sie Entwickler-Guides und die API-Referenz, testen Sie Code-Beispiele und Live-Demos, und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# Integration mit Angular {#integration-with-angular} + +:::tip +Grundkenntnisse der Konzepte und Muster von **Angular** werden vorausgesetzt. Zur Auffrischung lesen Sie die [**Angular-Dokumentation**](https://v17.angular.io/docs). +::: + +DHTMLX Pivot lässt sich wie eine reguläre Komponente in **Angular** einbinden. Ein vollständiges, lauffähiges Beispiel finden Sie in der [**Angular Pivot Demo auf GitHub**](https://github.com/DHTMLX/angular-pivot-demo). + +## Projekt erstellen {#create-a-project} + +:::info +Installieren Sie [**Angular CLI**](https://v1.angular.io/cli) und [**Node.js**](https://nodejs.org/en/), bevor Sie beginnen. +::: + +Der folgende Befehl erstellt ein neues Angular-Projekt mit dem Namen *my-angular-pivot-app*: + +~~~bash +ng new my-angular-pivot-app +~~~ + +:::note +Deaktivieren Sie Server-Side Rendering (SSR) und Static Site Generation (SSG/Prerendering), wenn die Angular CLI danach fragt — dieser Guide setzt eine client-seitig gerenderte App voraus. +::: + +Der Befehl installiert alle erforderlichen Werkzeuge. Weitere Befehle sind nicht notwendig. + +### Abhängigkeiten installieren {#install-dependencies} + +Wechseln Sie in das neue Projektverzeichnis: + +~~~bash +cd my-angular-pivot-app +~~~ + +Installieren Sie die Abhängigkeiten und starten Sie den Entwicklungsserver mit dem Paketmanager [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # oder: yarn dev +~~~ + +Die App sollte auf einem lokalen Port erreichbar sein (zum Beispiel `http://localhost:3000`). + +## Pivot erstellen {#create-pivot} + +Fügen Sie das Pivot-Paket zum Projekt hinzu und binden Sie Pivot anschließend in eine Angular-Komponente ein. + +### Schritt 1. Paket installieren {#step-1-install-the-package} + +Laden Sie das [**Pivot-Testpaket**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) herunter und folgen Sie den Anweisungen in der README-Datei. Das Testpaket ist 30 Tage gültig. + +### Schritt 2. Komponente erstellen {#step-2-create-the-component} + +Erstellen Sie eine Angular-Komponente, die Pivot einbindet. Legen Sie einen Ordner *pivot* unter *src/app/* an und erstellen Sie die Datei *src/app/pivot/pivot.component.ts*. Folgen Sie dann diesen Schritten: + +#### Quelldateien importieren {#import-source-files} + +Öffnen Sie *src/app/pivot/pivot.component.ts* und importieren Sie das Pivot-Paket. Der Import-Pfad hängt von der Paketedition ab: + +- **PRO-Version** (aus einem lokalen Ordner installiert): + +~~~jsx +import { Pivot } from 'dhx-pivot-package'; +~~~ + +- **Testversion**: + +~~~jsx +import { Pivot } from '@dhx/trial-pivot'; +~~~ + +Dieses Tutorial verwendet die Testversion von Pivot. + +#### Container einrichten und Pivot einbinden {#set-up-the-container-and-mount-pivot} + +Um Pivot auf der Seite anzuzeigen, definieren Sie ein Container-Element im Component-Template und initialisieren Sie Pivot im `ngOnInit`-Hook über den Konstruktor. Zerstören Sie Pivot im `ngOnDestroy`-Hook. + +Das folgende Code-Snippet definiert eine minimale Pivot Angular-Komponente: + +~~~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", // Template-Name, der in "app.component.ts" als verwendet wird + styleUrls: ["./pivot.component.css"], // CSS-Datei einbinden + template: `
`, +}) + +export class PivotComponent implements OnInit, OnDestroy { + // Container-Referenz für Pivot + @ViewChild('container', { static: true }) pivot_container!: ElementRef; + + private _table!: Pivot; + + ngOnInit() { + // Pivot-Komponente initialisieren + this._table = new Pivot(this.pivot_container.nativeElement, {}); + } + + ngOnDestroy(): void { + this._table.destructor(); // Pivot beim Entfernen zerstören + } +} +~~~ + +#### Stile hinzufügen {#add-styles} + +Damit Pivot korrekt gerendert wird, erstellen Sie *src/app/pivot/pivot.component.css* mit Stilen für die Seite und den Pivot-Container: + +~~~css title="pivot.component.css" +/* Pivot-Stile importieren */ +@import "@dhx/trial-pivot/dist/pivot.css"; + +/* Stile für die Startseite */ +html, +body { + margin: 0; + padding: 0; + height: 100%; +} + +/* Stile für den Pivot-Container */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### Daten laden {#load-data} + +Um Pivot mit Daten zu versorgen, bereiten Sie einen Datensatz vor. Erstellen Sie *src/app/pivot/data.ts* und exportieren Sie die Daten sowie die Feld-Metadaten: + +~~~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" + }, // weitere Datensätze + ]; + + const fields: any = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // weitere Felder + ]; + + return { dataset, fields }; +}; +~~~ + +Öffnen Sie *src/app/pivot/pivot.component.ts*, importieren Sie `getData` und wenden Sie den Datensatz in `ngOnInit()` an: + +~~~jsx {2,18,20-21} title="pivot.component.ts" +import { Pivot } from '@dhx/trial-pivot'; +import { getData } from "./data"; // Daten importieren +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(); // Daten und Feld-Metadaten entpacken + 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" + }, // weitere Werte + ] + }, + // weitere Konfigurationseigenschaften + }); + } + + ngOnDestroy(): void { + this._table.destructor(); + } +} +~~~ + +Die Komponente ist jetzt einsatzbereit. Beim Einbinden rendert Pivot die übergebenen Daten. Die vollständige Liste der Konfigurationseigenschaften finden Sie in der [Pivot API-Dokumentation](api/overview/properties-overview.md). + +#### Events behandeln {#handle-events} + +Benutzeraktionen in Pivot lösen Events aus, die Sie abonnieren können. Die vollständige Liste der Events finden Sie in der [Events-Übersicht](api/overview/events-overview.md). + +Das folgende Code-Snippet erweitert `ngOnInit` um einen `open-filter`-Event-Listener, der die Feld-ID protokolliert, wenn ein Benutzer einen Filter öffnet: + +~~~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" + }, // weitere Werte + ] + } + }); + + this._table.api.on("open-filter", (ev) => { + console.log("Die Feld-ID, für die der Filter aktiviert wird:", ev.id); + }); +} + +ngOnDestroy(): void { + this._table.destructor(); +} +~~~ + +### Schritt 3. Pivot zur App hinzufügen {#step-3-add-pivot-to-the-app} + +Um `PivotComponent` in die App einzubetten, öffnen Sie *src/app/app.component.ts* und ersetzen Sie den Standardcode durch Folgendes: + +~~~jsx {5} title="app.component.ts" +import { Component } from "@angular/core"; + +@Component({ + selector: "app-root", + template: `` // Template, das in "pivot.component.ts" erstellt wurde +}) +export class AppComponent { + name = ""; +} +~~~ + +Erstellen Sie dann *src/app/app.module.ts* und registrieren Sie `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 {} +~~~ + +Öffnen Sie abschließend *src/main.ts* und ersetzen Sie den Inhalt durch folgenden Bootstrap-Code: + +~~~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)); +~~~ + +Starten Sie die App, um zu sehen, wie Pivot die Daten auf der Seite rendert. + +![Pivot-Initialisierung](../assets/trial_pivot.png) + +Pivot ist nun in Angular integriert. Passen Sie die Konfiguration an die Anforderungen Ihres Projekts an. Das vollständige Beispiel finden Sie in der [**angular-pivot-demo auf GitHub**](https://github.com/DHTMLX/angular-pivot-demo). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-react.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-react.md new file mode 100644 index 0000000..f2f5797 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-react.md @@ -0,0 +1,289 @@ +--- +sidebar_label: Integration mit React +title: Integration mit React +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die Integration mit React. Erkunden Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Integration mit React {#integration-with-react} + +:::tip +Es werden grundlegende Kenntnisse der Konzepte und Muster von [**React**](https://react.dev) vorausgesetzt. Zur Auffrischung empfiehlt sich die [**React-Dokumentation**](https://react.dev/learn). +::: + +DHTMLX Pivot lässt sich als reguläre Komponente in **React** integrieren. Ein vollständiges Beispiel-Setup finden Sie in der [**React Pivot Demo auf GitHub**](https://github.com/DHTMLX/react-pivot-demo). + +## Projekt erstellen {#create-a-project} + +:::info +Installieren Sie [**Node.js**](https://nodejs.org/en/), bevor Sie beginnen. [**Vite**](https://vite.dev/) ist optional. +::: + +Erstellen Sie ein einfaches **React**-Projekt (oder ein Vite-basiertes) mit dem Namen *my-react-pivot-app*. + +Der folgende Befehl richtet ein Create React App-Projekt ein: + +~~~bash +npx create-react-app my-react-pivot-app +~~~ + +### Abhängigkeiten installieren {#install-dependencies} + +Wechseln Sie in das neue Projektverzeichnis: + +~~~bash +cd my-react-pivot-app +~~~ + +Installieren Sie die Abhängigkeiten und starten Sie den Dev-Server mit Ihrem Paketmanager: + +- mit [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # oder: yarn dev +~~~ + +- mit [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +Die Anwendung sollte auf einem lokalen Port laufen (beispielsweise `http://localhost:3000`). + +## Pivot erstellen {#create-pivot} + +Fügen Sie das Pivot-Paket zum Projekt hinzu und umschließen Sie Pivot anschließend mit einer React-Komponente. + +### Schritt 1. Paket installieren {#step-1-install-the-package} + +Laden Sie das [**Pivot-Testpaket**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) herunter und folgen Sie den Schritten in der README. Das Pivot-Testpaket ist 30 Tage gültig. + +### Schritt 2. Komponente erstellen {#step-2-create-the-component} + +Erstellen Sie eine React-Komponente, die Pivot einbindet. Legen Sie eine neue Datei *src/Pivot.jsx* an. + +#### Quelldateien importieren {#import-source-files} + +Öffnen Sie *src/Pivot.jsx* und importieren Sie die Pivot-Quelldateien. Die Import-Pfade hängen von der Paketedition ab: + +- **PRO-Version** (aus einem lokalen Ordner installiert): + +~~~jsx title="Pivot.jsx" +import { Pivot } from 'dhx-pivot-package'; +import 'dhx-pivot-package/dist/pivot.css'; +~~~ + +Falls das Paket minifizierte Assets enthält, importieren Sie statt *pivot.css* die Datei *pivot.min.css*. + +- **Testversion**: + +~~~jsx title="Pivot.jsx" +import { Pivot } from '@dhx/trial-pivot'; +import "@dhx/trial-pivot/dist/pivot.css"; +~~~ + +Dieses Tutorial verwendet die Testversion von Pivot. + +#### Container einrichten und Pivot einbinden {#set-up-the-container-and-mount-pivot} + +Um Pivot auf der Seite anzuzeigen, erstellen Sie ein Container-`div` und initialisieren Sie Pivot anschließend in einem `useEffect`-Hook mithilfe des Konstruktors. + +Das folgende Code-Snippet definiert eine minimale Pivot-React-Komponente: + +~~~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-Styles einbinden + +export default function PivotComponent(props) { + let container = useRef(); // Container-Ref für Pivot + + useEffect(() => { + // die Pivot-Komponente initialisieren + const table = new Pivot(container.current, {}); + + return () => { + table.destructor(); // Pivot beim Unmount zerstören + }; + }, []); + + return
; +} +~~~ + +#### Styles hinzufügen {#add-styles} + +Damit Pivot korrekt dargestellt wird, fügen Sie die folgenden Styles zur CSS-Hauptdatei des Projekts hinzu: + +~~~css title="index.css" +/* Styles für die Ausgangsseite */ +html, +body, +#root { + height: 100%; + padding: 0; + margin: 0; +} + +/* Styles für den Pivot-Container */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### Daten laden {#load-data} + +Um Pivot mit Daten zu versorgen, bereiten Sie einen Datensatz vor. Erstellen Sie *src/data.js* und exportieren Sie die Daten sowie die Feld-Metadaten: + +~~~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" + }, // weitere Dateneinträge + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // weitere Felder + ]; + + return { dataset, fields }; +}; +~~~ + +Öffnen Sie *src/App.js*, importieren Sie die Daten und übergeben Sie diese als Props an die ``-Komponente: + +~~~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; +~~~ + +Öffnen Sie *src/Pivot.jsx*, destrukturieren Sie die Props und wenden Sie diese auf das Pivot-Konfigurationsobjekt an: + +~~~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" + }, // weitere Werte + ] + }, + // weitere Konfigurationseigenschaften + }); + + return () => { + table.destructor(); + } + }, []); + + return
; +} +~~~ + +Die Komponente ist nun einsatzbereit. Beim Einbinden rendert Pivot mit den bereitgestellten Daten. Die vollständige Liste der Konfigurationseigenschaften finden Sie in der [Pivot-API-Dokumentation](api/overview/properties-overview.md). + +#### Events verarbeiten {#handle-events} + +Benutzeraktionen in Pivot lösen Events aus, die Sie abonnieren können. Die vollständige Liste der Events finden Sie in der [Events-Übersicht](api/overview/events-overview.md). + +Das folgende Code-Snippet erweitert `useEffect` um einen `open-filter`-Event-Listener, der die Feld-ID protokolliert, wenn ein Benutzer einen Filter öffnet: + +~~~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" + }, // weitere Werte + ] + }, + // weitere Konfigurationseigenschaften + }); + + table.api.on("open-filter", (ev) => { + console.log("Die Feld-ID, für die der Filter aktiviert wurde:", ev.id); + }); + + return () => { + table.destructor(); + } +}, []); +// ... +~~~ + +Starten Sie die Anwendung, um zu sehen, wie Pivot die Daten auf der Seite rendert. + +![Pivot-Initialisierung](../assets/trial_pivot.png) + +Pivot ist nun in React integriert. Passen Sie die Konfiguration an die Projektanforderungen an. Das vollständige Beispiel finden Sie in der [**react-pivot-demo auf GitHub**](https://github.com/DHTMLX/react-pivot-demo). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md new file mode 100644 index 0000000..0a62df4 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-svelte.md @@ -0,0 +1,302 @@ +--- +sidebar_label: Integration mit Svelte +title: Integration mit Svelte +description: Sie können mehr über die Integration mit Svelte in der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren. Durchsuchen Sie Entwicklerhandbücher und API-Referenz, probieren Sie Codebeispiele und Live-Demos aus, und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# Integration mit Svelte {#integration-with-svelte} + +:::tip +Grundkenntnisse der Konzepte und Muster von **Svelte** werden vorausgesetzt. Zur Auffrischung lesen Sie die [**Svelte-Dokumentation**](https://svelte.dev/). +::: + +DHTMLX Pivot lässt sich als reguläre Komponente in **Svelte** integrieren. Ein vollständiges, funktionsfähiges Setup finden Sie in der [**Svelte Pivot-Demo auf GitHub**](https://github.com/DHTMLX/svelte-pivot-demo). + +## Projekt erstellen {#create-a-project} + +:::info +Installieren Sie [**Node.js**](https://nodejs.org/en/) bevor Sie beginnen. [**Vite**](https://vite.dev/) ist optional. +::: + +Der folgende Befehl führt das Vite-Projektgerüst-Tool aus und ermöglicht die Auswahl einer Svelte-Vorlage: + +~~~bash +npm create vite@latest +~~~ + +Benennen Sie das Projekt *my-svelte-pivot-app*. + +### Abhängigkeiten installieren {#install-dependencies} + +Wechseln Sie in das neu erstellte Projektverzeichnis: + +~~~bash +cd my-svelte-pivot-app +~~~ + +Installieren Sie die Abhängigkeiten und starten Sie den Entwicklungsserver mit Ihrem Paketmanager: + +- mit [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # oder: yarn dev +~~~ + +- mit [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +Die App sollte auf einem lokalen Port laufen (zum Beispiel `http://localhost:3000`). + +## Pivot erstellen {#create-pivot} + +Fügen Sie das Pivot-Paket zum Projekt hinzu und binden Sie Pivot anschließend in eine Svelte-Komponente ein. + +### Schritt 1. Paket installieren {#step-1-install-the-package} + +Laden Sie das [**Test-Pivot-Paket**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) herunter und folgen Sie den Schritten in der README-Datei. Das Test-Pivot-Paket ist 30 Tage gültig. + +### Schritt 2. Komponente erstellen {#step-2-create-the-component} + +Erstellen Sie eine Svelte-Komponente, die Pivot einbindet. Fügen Sie eine neue Datei *src/Pivot.svelte* hinzu. + +#### Quelldateien importieren {#import-source-files} + +Öffnen Sie *src/Pivot.svelte* und importieren Sie die Pivot-Quelldateien. Die Import-Pfade hängen von der Paketversion ab: + +- **PRO-Version** (aus einem lokalen Ordner installiert): + +~~~html title="Pivot.svelte" + +~~~ + +Wenn das Paket minimierte Assets enthält, importieren Sie *pivot.min.css* anstelle von *pivot.css*. + +- **Testversion**: + +~~~html title="Pivot.svelte" + +~~~ + +Dieses Tutorial verwendet die Testversion von Pivot. + +#### Container einrichten und Pivot einbinden {#set-up-the-container-and-mount-pivot} + +Um Pivot auf der Seite anzuzeigen, fügen Sie ein Container-`div` hinzu und initialisieren Sie Pivot dann im `onMount`-Lifecycle-Hook mithilfe des Konstruktors. Zerstören Sie Pivot im `onDestroy`-Hook. + +Der folgende Code-Ausschnitt definiert eine minimale Pivot-Svelte-Komponente: + +~~~html {3,6,10-11,19} title="Pivot.svelte" + + +
+~~~ + +#### Styles hinzufügen {#add-styles} + +Damit Pivot korrekt gerendert wird, fügen Sie die folgenden Styles zur CSS-Hauptdatei des Projekts hinzu: + +~~~css title="main.css" +/* Styles für die Startseite */ +html, +body, +#app { /* #app-Root-Container verwenden */ + height: 100%; + padding: 0; + margin: 0; +} + +/* Styles für den Pivot-Container */ +.widget { + height: 100%; + width: 100%; +} +~~~ + +#### Daten laden {#load-data} + +Um Pivot mit Daten zu versorgen, bereiten Sie einen Datensatz vor. Erstellen Sie *src/data.js* und exportieren Sie die Daten und Feld-Metadaten: + +~~~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" + }, // weitere Datensätze + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // weitere Felder + ]; + + return { dataset, fields }; +}; +~~~ + +Öffnen Sie *src/App.svelte*, importieren Sie die Daten und übergeben Sie sie als Props an die neue ``-Komponente: + +~~~html {3,5,8} title="App.svelte" + + + +~~~ + +Öffnen Sie *src/Pivot.svelte*, deklarieren Sie die eingehenden Props mit `export let` und wenden Sie sie auf das Pivot-Konfigurationsobjekt an: + +~~~html {6-7,14-15} title="Pivot.svelte" + + +
+~~~ + +Die Komponente ist nun einsatzbereit. Beim Einbinden rendert Pivot mit den übergebenen Daten. Die vollständige Liste der Konfigurationseigenschaften finden Sie in der [Pivot-API-Dokumentation](api/overview/properties-overview.md). + +#### Events behandeln {#handle-events} + +Benutzeraktionen in Pivot lösen Events aus, die Sie abonnieren können. Die vollständige Liste der Events finden Sie in der [Übersicht der Events](api/overview/events-overview.md). + +Der folgende Code-Ausschnitt erweitert `onMount` um einen `open-filter`-Event-Listener, der die Feld-ID protokolliert, wenn ein Benutzer einen Filter öffnet: + +~~~html {22-24} title="Pivot.svelte" + + +// ... +~~~ + +Starten Sie die App, um zu sehen, wie Pivot die Daten auf der Seite rendert. + +![Pivot-Initialisierung](../assets/trial_pivot.png) + +Pivot ist nun in Svelte integriert. Passen Sie die Konfiguration an die Anforderungen Ihres Projekts an. Das vollständige Beispiel finden Sie in der [**svelte-pivot-demo auf GitHub**](https://github.com/DHTMLX/svelte-pivot-demo). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md new file mode 100644 index 0000000..c3f3c8d --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/integration-with-vue.md @@ -0,0 +1,312 @@ +--- +sidebar_label: Integration mit Vue +title: Integration mit Vue +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie alles über die Integration mit Vue. Lesen Sie Entwickleranleitungen und die API-Referenz, probieren Sie Code-Beispiele und Live-Demos aus, und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Integration mit Vue {#integration-with-vue} + +:::tip +Grundkenntnisse der Konzepte und Muster von [**Vue**](https://vuejs.org/) werden vorausgesetzt. Zur Auffrischung lesen Sie die [**Vue-3-Dokumentation**](https://vuejs.org/guide/introduction.html#getting-started). +::: + +DHTMLX Pivot lässt sich als reguläre Komponente in **Vue** einbinden. Ein vollständiges Arbeitsbeispiel finden Sie in der [**Vue-Pivot-Demo auf GitHub**](https://github.com/DHTMLX/vue-pivot-demo). + +## Projekt erstellen {#create-a-project} + +:::info +Installieren Sie [**Node.js**](https://nodejs.org/en/), bevor Sie beginnen. +::: + +Der folgende Befehl startet das offizielle **Vue**-Projektgerüst-Tool: + +~~~bash +npm create vue@latest +~~~ + +Der Befehl installiert und führt `create-vue` aus. Weitere Informationen finden Sie im [Vue.js Quick Start](https://vuejs.org/guide/quick-start.html#creating-a-vue-application). + +Nennen Sie das Projekt *my-vue-pivot-app*. + +### Abhängigkeiten installieren {#install-dependencies} + +Wechseln Sie in das neue Projektverzeichnis: + +~~~bash +cd my-vue-pivot-app +~~~ + +Installieren Sie die Abhängigkeiten und starten Sie den Entwicklungsserver mit Ihrem Paketmanager: + +- mit [**yarn**](https://yarnpkg.com/): + +~~~bash +yarn +yarn start # oder: yarn dev +~~~ + +- mit [**npm**](https://www.npmjs.com/): + +~~~bash +npm install +npm run dev +~~~ + +Die App sollte auf einem lokalen Port verfügbar sein (zum Beispiel `http://localhost:3000`). + +## Pivot erstellen {#create-pivot} + +Fügen Sie das Pivot-Paket zum Projekt hinzu und binden Sie Pivot in eine Vue-Komponente ein. + +### Schritt 1. Paket installieren {#step-1-install-the-package} + +Laden Sie das [**Pivot-Testpaket**](how-to-start.md#installing-trial-pivot-via-npm-or-yarn) herunter und befolgen Sie die Schritte in der README. Das Pivot-Testpaket ist 30 Tage gültig. + +### Schritt 2. Komponente erstellen {#step-2-create-the-component} + +Erstellen Sie eine Vue-Komponente, die Pivot einbindet. Legen Sie die neue Datei *src/components/Pivot.vue* an. + +#### Quelldateien importieren {#import-source-files} + +Öffnen Sie *src/components/Pivot.vue* und importieren Sie die Pivot-Quelldateien. Die Import-Pfade hängen von der Paketedition ab: + +- **PRO-Version** (aus einem lokalen Ordner installiert): + +~~~html title="Pivot.vue" + +~~~ + +Falls das Paket minimierte Assets enthält, importieren Sie *pivot.min.css* statt *pivot.css*. + +- **Testversion**: + +~~~html title="Pivot.vue" + +~~~ + +Dieses Tutorial verwendet die Testversion von Pivot. + +#### Container einrichten und Pivot einbinden {#set-up-the-container-and-mount-pivot} + +Um Pivot auf der Seite anzuzeigen, fügen Sie ein Container-`div` hinzu und initialisieren Sie Pivot im `mounted`-Hook mithilfe des Konstruktors. Zerstören Sie Pivot im `unmounted`-Hook. + +Der folgende Code-Ausschnitt definiert eine minimale Pivot-Vue-Komponente: + +~~~html {2,7-8,18} title="Pivot.vue" + + + +~~~ + +#### Styles hinzufügen {#add-styles} + +Damit Pivot korrekt gerendert wird, fügen Sie die folgenden Styles in die CSS-Hauptdatei des Projekts ein: + +~~~css title="style.css" +/* Styles für die initiale Seite */ +html, +body, +#app { /* den #app-Root-Container verwenden */ + height: 100%; + padding: 0; + margin: 0; +} + +/* Styles für den Pivot-Container */ +.widget { + width: 100%; + height: 100%; +} +~~~ + +#### Daten laden {#load-data} + +Um Daten in Pivot zu laden, bereiten Sie einen Datensatz vor. Erstellen Sie *src/data.js* und exportieren Sie die Daten sowie die Feld-Metadaten: + +~~~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" + }, // weitere Dateneinträge + ]; + + const fields = [ + { + "id": "cogs", + "label": "Cogs", + "type": "number" + }, + { + "id": "date", + "label": "Date", + "type": "date" + }, // weitere Felder + ]; + + return { dataset, fields }; +}; +~~~ + +Öffnen Sie *src/App.vue*, importieren Sie die Daten, und stellen Sie sie über die `data()`-Option bereit. Übergeben Sie die Werte dann als Props an die neue ``-Komponente: + +~~~html {3,7-13,18} title="App.vue" + + + +~~~ + +Öffnen Sie *src/components/Pivot.vue*, deklarieren Sie die eingehenden Props, und wenden Sie sie auf das Pivot-Konfigurationsobjekt an: + +~~~html {6,10-11} title="Pivot.vue" + + + +~~~ + +Die Komponente ist nun einsatzbereit. Beim Einbinden rendert Pivot mit den übergebenen Daten. Die vollständige Liste der Konfigurationseigenschaften finden Sie in der [Pivot-API-Dokumentation](api/overview/properties-overview.md). + +#### Events verarbeiten {#handle-events} + +Benutzeraktionen in Pivot lösen Events aus, die Sie abonnieren können. Die vollständige Liste der Events finden Sie in der [Events-Übersicht](api/overview/events-overview.md). + +Der folgende Code-Ausschnitt erweitert `mounted` um einen `open-filter`-Event-Listener, der die Feld-ID protokolliert, wenn ein Benutzer einen Filter öffnet: + +~~~html {22-24} title="Pivot.vue" + + +// ... +~~~ + +Starten Sie die App, um zu sehen, wie Pivot die Daten auf der Seite rendert. + +![Pivot-Initialisierung](../assets/trial_pivot.png) + +Pivot ist nun in Vue integriert. Passen Sie die Konfiguration an die Anforderungen Ihres Projekts an. Das vollständige Beispiel finden Sie in der [**vue-pivot-Demo auf GitHub**](https://github.com/DHTMLX/vue-pivot-demo). diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/loading-data.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/loading-data.md new file mode 100644 index 0000000..76201e6 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/loading-data.md @@ -0,0 +1,279 @@ +--- +sidebar_label: Daten laden +title: Daten laden +description: Sie erfahren hier, wie Sie Daten in der DHTMLX JavaScript Pivot-Bibliothek laden. Lesen Sie Entwicklerhandbücher und die API-Referenz, probieren Sie Codebeispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Testversion von DHTMLX Pivot herunter. +--- + +# Daten laden {#loading-data} + +Pivot akzeptiert Daten im JSON-Format über die [`data`](api/config/data-property.md)-Eigenschaft. Pivot unterstützt außerdem CSV-Daten nach der Konvertierung in JSON. + +## Daten für das Laden vorbereiten {#prepare-data-for-loading} + +Die [`data`](api/config/data-property.md)-Eigenschaft akzeptiert ein Array von Objekten, wobei jedes Objekt eine Datenzeile repräsentiert. Die Schlüssel jedes Objekts definieren die Dimensionen und Werte, die in der Pivot-Tabelle verwendet werden. + +Das folgende Code-Snippet definiert ein Beispiel-`data`-Array: + +~~~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") + }, + // weitere Daten +]; +~~~ + +:::info +Informationen zur Definition von Feldern und der Pivot-Struktur finden Sie unter [Mit Daten arbeiten](guides/working-with-data.md). +::: + +## Daten aus einer Datei laden {#load-data-from-a-file} + +Pivot lädt JSON-Daten nach der Initialisierung aus einer externen Datei. Bereiten Sie eine Quelldatei mit den Daten, Feldern und der Konfiguration vor. + +Das folgende Code-Snippet definiert `data`, `fields` und einen `getData()`-Accessor in einer separaten Datei: + +~~~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") + }, + // weitere Daten +]; +~~~ + +Fügen Sie den Pfad zur Quelldatendatei im Seiten-Markup hinzu: + +~~~html title="index.html" + + + + +~~~ + +Das folgende Code-Snippet erstellt Pivot und lädt Daten aus der vorbereiteten Datei: + +~~~jsx +const { data, config, fields } = getData(); +const table = new pivot.Pivot("#root", { data, config, fields }); +~~~ + +## Daten von einem Server laden {#load-data-from-a-server} + +Um Daten von einem Server-Endpunkt zu laden, senden Sie eine Anfrage mit der nativen `fetch`-Methode (oder einer gleichwertigen Alternative) und übergeben Sie die Antwort dann an [`setConfig`](api/methods/setconfig-method.md), das die Pivot-Konfiguration aktualisiert und zuvor gesetzte Optionen beibehält. + +Das folgende Code-Snippet initialisiert Pivot mit leeren Daten, ruft Daten und Felder von einem Server ab und wendet sie dann mit `setConfig` an: + +~~~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 }); +}); +~~~ + +Weitere Informationen finden Sie im folgenden Thema: [Mit dem Server arbeiten](/guides/working-with-server) + +## CSV-Daten laden {#load-csv-data} + +Pivot akzeptiert CSV-Daten, nachdem Sie diese mit einer externen JS-Parsing-Bibliothek in JSON konvertiert haben. Die konvertierten Daten verhalten sich genauso wie natives JSON. + +Das folgende Beispiel verwendet die externe [PapaParse](https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.4.1/papaparse.min.js)-Bibliothek, um Daten bei einem Button-Klick zu laden und zu konvertieren. Der `convert()`-Helfer nimmt folgende Parameter entgegen: + +- `data` — ein String mit CSV-Daten +- `headers` — ein Array mit CSV-Feldnamen +- `meta` — ein Objekt, das Feldnamen auf Datentypen abbildet + +Das folgende Code-Snippet erstellt Pivot, definiert den `convert()`-Helfer und wendet die geparsten CSV-Daten über [`setConfig`](api/methods/setconfig-method.md) bei einem Button-Klick an: + +~~~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" + ]; + + // Datumsfelder explizit markieren für korrekte Konvertierung + 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); +~~~ + +## Beispiel {#example} + +Das folgende Snippet lädt JSON- und CSV-Daten: + + + +**Verwandte Beispiele**: +- [Pivot 2. Datumsformat](https://snippet.dhtmlx.com/shn1l794) +- [Pivot 2. Verschiedene Datensätze](https://snippet.dhtmlx.com/6xtqge4i) +- [Pivot 2. Großer Datensatz](https://snippet.dhtmlx.com/e6qwqrys) + +**Verwandte Artikel**: [Datumsformatierung](guides/localization.md#date-formatting) diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/localization.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/localization.md new file mode 100644 index 0000000..4a2fb74 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/localization.md @@ -0,0 +1,293 @@ +--- +sidebar_label: Lokalisierung +title: Lokalisierung +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die Lokalisierung. Entwickleranleitungen und API-Referenz, Code-Beispiele und Live-Demos sowie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot. +--- + +# Lokalisierung {#localization} + +Pivot ermöglicht es Ihnen, jede Beschriftung in der Oberfläche zu lokalisieren. Erstellen Sie eine neue Locale oder ändern Sie eine vorhandene, und wenden Sie die Locale dann über die Eigenschaft [`locale`](api/config/locale-property.md) oder die Methode [`setLocale`](api/methods/setlocale-method.md) auf Pivot an. + +## Standard-Locale {#default-locale} + +Pivot verwendet standardmäßig die englische Locale. Der folgende Code-Ausschnitt zeigt die Struktur der integrierten `en`-Locale: + +~~~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", +}; +~~~ + +## Locale anwenden {#apply-a-locale} + +Pivot stellt drei integrierte Locales über das Objekt `pivot.locales` bereit: `en`, `de` und `cn`. Übergeben Sie eine integrierte Locale bei der Initialisierung an die Eigenschaft [`locale`](api/config/locale-property.md). + +Der folgende Code-Ausschnitt initialisiert Pivot mit der deutschen Locale: + +~~~jsx +new pivot.Pivot("#root", { + // other properties + locale: pivot.locales.de, +}); +~~~ + +So wenden Sie eine benutzerdefinierte Locale an: + +- Erstellen Sie ein Locale-Objekt (oder ändern Sie ein vorhandenes) und stellen Sie Übersetzungen für alle Textbeschriftungen bereit (in einer beliebigen Sprache). +- Wenden Sie die Locale über die Eigenschaft [`locale`](api/config/locale-property.md) oder die Methode [`setLocale`](api/methods/setlocale-method.md) auf Pivot an. + +Der folgende Code-Ausschnitt erstellt Pivot und wendet dann zur Laufzeit mit `setLocale` eine benutzerdefinierte koreanische Locale an: + +~~~jsx +// create Pivot +const widget = new pivot.Pivot("#root", { + data, + // other configuration properties +}); + +const ko = { /* object with locale */ }; +widget.setLocale(ko); +~~~ + +:::tip +Rufen Sie [`setLocale`](api/methods/setlocale-method.md) ohne Argumente (oder mit `null`) auf, um Pivot auf die englische Standard-Locale zurückzusetzen. +::: + +## Datumsformate {#date-formatting} + +Pivot akzeptiert Datumsangaben als `Date`-Objekte. Wandeln Sie Zeichenkettenwerte in `Date` um, bevor Sie Daten an Pivot übergeben. Das standardmäßige `dateFormat` ist `"%d.%m.%Y"` und wird aus der aktuellen Locale übernommen. + +Um das Format für alle Datumsfelder zu ändern, setzen Sie einen neuen Wert für `dateFormat` im Objekt `formats` der Eigenschaft [`locale`](api/config/locale-property.md). + +Der folgende Code-Ausschnitt wandelt Datumszeichenketten in `Date`-Objekte um, initialisiert dann Pivot mit einem benutzerdefinierten `dateFormat` und aktualisiert das Format zur Laufzeit über `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" + } + ] + } +}); +~~~ + +Um ein benutzerdefiniertes Format für ein bestimmtes Feld festzulegen, verwenden Sie den Parameter `format` der Eigenschaft [`fields`](api/config/fields-property.md). Siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields). + +## Zeichen für Datum- und Zeitformat {#date-and-time-format-characters} + +Pivot verwendet die folgenden Zeichen, um das Datum- und Zeitformat zu definieren: + +| Zeichen | Definition | Beispiel | +| :-------- | :------------------------------------------------------------ | :------------------------ | +| %d | Tag als Zahl mit führender Null | von 01 bis 31 | +| %j | Tag als Zahl | von 1 bis 31 | +| %D | Kurzname des Wochentags (Abkürzung) | So Mo Di Sa | +| %l | Vollständiger Name des Wochentags | Sonntag Montag Dienstag | +| %W | Woche als Zahl mit führender Null (mit Montag als erstem Wochentag) | von 01 bis 52/53 | +| %m | Monat als Zahl mit führender Null | von 01 bis 12 | +| %n | Monat als Zahl | von 1 bis 12 | +| %M | Kurzname des Monats | Jan Feb Mär | +| %F | Vollständiger Name des Monats | Januar Februar März | +| %y | Jahr als Zahl, 2-stellig | 24 | +| %Y | Jahr als Zahl, 4-stellig | 2024 | +| %h | Stunden im 12-Stunden-Format mit führender Null | von 01 bis 12 | +| %g | Stunden im 12-Stunden-Format | von 1 bis 12 | +| %H | Stunden im 24-Stunden-Format mit führender Null | von 00 bis 23 | +| %G | Stunden im 24-Stunden-Format | von 0 bis 23 | +| %i | Minuten mit führender Null | von 01 bis 59 | +| %s | Sekunden mit führender Null | von 01 bis 59 | +| %S | Millisekunden | 128 | +| %a | am oder pm | am (für die Zeit von Mitternacht bis Mittag) und pm (für die Zeit von Mittag bis Mitternacht)| +| %A | AM oder PM | AM (für die Zeit von Mitternacht bis Mittag) und PM (für die Zeit von Mittag bis Mitternacht)| +| %c | Zeigt Datum und Uhrzeit im ISO-8601-Format an | 2024-10-04T05:04:09 | + +Um den 20. September 2024 um 16:47:08.128 als *2024-09-20 16:47:08.128* darzustellen, verwenden Sie das Format `"%Y-%m-%d %H:%i:%s.%S"`. + +## Zahlenformate {#number-formatting} + +Pivot lokalisiert alle `number`-Felder anhand des `lang`-Werts der aktuellen Locale. Das Widget verwendet die Spezifikation [`Intl.NumberFormat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat). Die Standardeinstellungen begrenzen die Nachkommastellen auf 3 und wenden Tausendergruppentrennzeichen auf den ganzzahligen Teil an. + +Um die Formatierung für ein bestimmtes numerisches Feld zu deaktivieren oder ein benutzerdefiniertes Format festzulegen, verwenden Sie den Parameter `format` der Eigenschaft [`fields`](api/config/fields-property.md). Setzen Sie `format` auf `false`, um die Formatierung zu deaktivieren, oder auf ein Objekt mit Format-Einstellungen (siehe [Formate auf Felder anwenden](guides/working-with-data.md#applying-formats-to-fields)). + +Der folgende Code-Ausschnitt deaktiviert die Zahlenformatierung für das Feld `year`: + +~~~jsx +const fields = [ + { id: "year", label: "Year", type: "number", format: false }, +]; +~~~ + +## Beispiel {#example} + +Der folgende Ausschnitt wechselt zwischen mehreren Locales: + + diff --git a/i18n/de/docusaurus-plugin-content-docs/current/guides/stylization.md b/i18n/de/docusaurus-plugin-content-docs/current/guides/stylization.md new file mode 100644 index 0000000..730b3b6 --- /dev/null +++ b/i18n/de/docusaurus-plugin-content-docs/current/guides/stylization.md @@ -0,0 +1,266 @@ +--- +sidebar_label: Gestaltung +title: Gestaltung +description: In der Dokumentation der DHTMLX JavaScript Pivot-Bibliothek erfahren Sie mehr über die Gestaltungsmöglichkeiten. Durchsuchen Sie Entwicklerhandbücher und API-Referenzen, probieren Sie Code-Beispiele und Live-Demos aus und laden Sie eine kostenlose 30-Tage-Evaluierungsversion von DHTMLX Pivot herunter. +--- + +# Gestaltung {#styling} + +Pivot wird mit einem Standard-Theme geliefert und stellt CSS-Variablen sowie Hilfsklassen zur Anpassung bereit. Überschreiben Sie die Variablen am Widget-Container (oder einem übergeordneten Element), um Farben, Rahmen und andere visuelle Eigenschaften zu ändern. + +## Standard-Style {#default-style} + +Das Standard-Theme von Pivot ist **Material**. Der folgende CSS-Ausschnitt zeigt die Variablen, die das Material-Theme am Widget-Container setzt: + +~~~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 Hinweis +Zukünftige Versionen von Pivot können CSS-Variablen umbenennen. Überprüfen Sie die Variablennamen nach einem Upgrade und aktualisieren Sie diese in Ihrem Code, um Darstellungsprobleme zu vermeiden. +::: + +## Integriertes Theme {#built-in-theme} + +Pivot bietet ein integriertes Theme: **Material**. Wenden Sie das Theme an, indem Sie entweder die Theme-Klasse zum Widget-Container hinzufügen oder das vorgefertigte Skin-Stylesheet auf der Seite einbinden. + +Der folgende Code-Ausschnitt wendet das Material-Theme an, indem die Klasse `wx-material-theme` zum Widget-Container hinzugefügt wird: + +~~~html {} + +
+~~~ + +Der folgende Code-Ausschnitt bindet das Material-Skin-Stylesheet direkt ein: + +~~~html {} + +~~~ + +## Integriertes Theme anpassen {#customize-built-in-theme} + +Überschreiben Sie die Material-Theme-Variablen am Selektor `.wx-material-theme`, um Farben, Rahmen und andere visuelle Eigenschaften zu ändern. + +Das folgende Beispiel überschreibt Material-Theme-Variablen, um Pivot in einem dunklen Farbschema darzustellen: + +~~~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: [ {