fix(docs): Add how to generate CSVs.

This commit is contained in:
Sandile 2021-10-07 13:15:33 +02:00
parent 9800f91a7a
commit 2cc8e45b16
3 changed files with 207 additions and 0 deletions

View File

@ -0,0 +1,201 @@
# Copyright 2020-2021 Lowdefy, Inc
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
_ref:
path: templates/general.yaml.njk
vars:
pageId: generate-csv
pageTitle: Generate CSVs
section: How To
filePath: howto/generate-csv.yaml
content:
- id: md1
type: MarkdownWithCode
properties:
style:
text-align: left
content: |
## How to Generate a CSV
Adding the functionality to generate a CSV file in Lowdefy can be accomplished by using a custom JS Action. This is a link to a simple JavaScript function that compiles a CSV from data that is available within the Lowdefy app.
### Steps to generate a CSV file in a Lowdefy app
1) Create an app directory
2) Initialise and start the Lowdefy app
3) Add the CSV JavaScript function to the app
4) Add a JsAction to a button with parameters populated
### 1. Create an app directory
This step assumes that you are beginning from scratch and have not created a Lowdefy app, if you already have a Lowdefy app initialised then you can skip this step.
1) Create a empty folder.
2) Open your terminal or cmd and `cd` to your empty folder.
### 2. Initialise and start the Lowdefy app
This step allows you to begin writing and running a Lowdefy app from within the folder that you created.
1) Run `npx lowdefy@latest init` to initialize
2) Run `npx lowdefy@latest dev` to start your Lowdefy app.
Once your Lowdefy app has been initialised, you will be able to edit code for a simple Welcome page which we will use to trigger a JsAction that generates a CSV.
Any changes that you make to the `lowdefy.yaml` file and the files within the app directory will be reflected in the Browser which will reload the page.
### 3. Add the CSV JavaScript function to the app
Custom JavaScript code can be added to a Lowdefy app to allow it to accomplish things that extend the functionality of Lowdefy. Let's create a custom action which will generate a CSV based on a JavaScript function called `csvMakeFn`.
1) Create a `public` folder inside your Lowdefy working directory.
2) Since all content in the `public` folder is served by the Lowdefy server, simply create a `csvMake.js` file inside the `public` folder.
3) Add this script to the file and save.
```js
const csvMakeFn = async (
context,
filename,
data,
fields,
) => {
if (!Array.isArray(data) || typeof data[0] !== 'object') {
throw new Error('csvMake data takes an array of objects');
}
if (!fields) {
fields = Object.keys(data[0]);
}
const arrays = [fields];
data.forEach(obj => arrays.push(fields.map(field => obj[field])));
const csv = arrays.map(row =>
row
.map(cell => typeof cell === 'undefined' || cell === null ? '' : cell)
.map(String)
.map(v => v.replaceAll('"', '""'))
.map(v => `"${v}"`)
.join(',')
).join('\r\n');
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const el = document.createElement('a');
el.href = url;
el.setAttribute('download', filename);
el.click();
};
window.lowdefy.registerJsAction('csvMake', csvMakeFn);
```
This script gets a few things done, firstly a csvMake function is defined and it checks if an array of data has been provided and whether the CSV fields have been populated. It then creates an array with fields and adds the provided data to the array according to the field definition. Once this is done a file which can be downloaded is generated using the array.
It is important to note that in order to call this function from within your Lowdefy app, it needs to be registered as a JsAction. Once this is done, you can simply write an Action that calls this function along with parameters.
4) With our JavaScript ready, we need to load the JavaScript onto our page in order for it to be evaluated by the browser.
To include an external JavaScript file, we use the script tag and add an `app` property to the `lowdefy.yaml` file in the root directory of the Lowdefy app similar to the example below:
```yaml
# ...
name: Lowdefy starter
app:
html:
appendHead: |
<script type="module" src="/public/csvMake.js"></script>
pages:
# ...
```
Once this is done, the JavaScript code will be linked to the Lowdefy app using the script tag which is added to the header of the HTML file viewed using the browser.
### 4. Add a JsAction to a button with parameters populated.
Lowdefy actions are triggered by page events, like `onClick` when a user clicks a button, or `onEnter` when the page loads. Lowdefy comes with a list of predefined actions, however, sometimes nothing beats adding custom code.
By default Lowdefy builds apps with a set of pre-configured, default block types to make it easier to build apps, for example using [`Button`](/Button), [`TextInput`](/TextInput), [`Box`](/Box), etc. All the blocks documented in the Lowdefy docs are default types.
We will be using a [`Button`](/Button) with an `onClick` event to trigger the custom JsAction that will generate the CSV using the data that is provided.
1) Populate an array with the arguments to be sent as parameters (csv filename, data, field definitions) to the custom JsAction as shown below:
```yaml
- profiles.csv # csv filename
- - Username: booker12 # an array of data
Identifier: 9012
FirstName: Rachel
LastName: Booker
- Username: grey07
Identifier: 2070
FirstName: Laura
LastName: Grey
- Username: johnson81
Identifier: 4081
FirstName: Craig
LastName: Johnson
- Username: jenkins46
Identifier: 9346
FirstName: Mary
LastName: Jenkins
- Username: smith79
Identifier: 5079
FirstName: Jamie
LastName: Smith
- - Username # an array of field definitions
- Identifier
- FirstName
- LastName
```
2) Edit the `docs_button` in the Welcome page to include the JsAction as shown below:
```yaml
- id: docs_button
type: Button
properties:
size: large
title: Let's build something
color: '#1890ff'
events:
onClick:
- id: generate_csv
type: JsAction
params:
name: csvMake
args:
- profiles.csv
- - Username: booker12
Identifier: 9012
FirstName: Rachel
LastName: Booker
- Username: grey07
Identifier: 2070
FirstName: Laura
LastName: Grey
- Username: johnson81
Identifier: 4081
FirstName: Craig
LastName: Johnson
- Username: jenkins46
Identifier: 9346
FirstName: Mary
LastName: Jenkins
- Username: smith79
Identifier: 5079
FirstName: Jamie
LastName: Smith
- - Username
- Identifier
- FirstName
- LastName
```
Congratulations, your custom JSAction is now available in your Lowdefy app and ready to use to generate a CSV with the click of the `docs_button`.

View File

@ -53,6 +53,11 @@
title: How To
icon: QuestionOutlined
links:
- id: generate-csv
type: MenuLink
pageId: generate-csv
properties:
title: Generate CSVs
- id: generate-pdf
type: MenuLink
pageId: generate-pdf-document-from-data

View File

@ -11,6 +11,7 @@
- _ref: tutorial/tutorial-deploy.yaml
- _ref: tutorial/next-steps.yaml
- _ref: howto/generate-csv.yaml
- _ref:
path: howto/generate-pdf.yaml.njk
vars: