@vivaconagua/vueca
TypeScript icon, indicating that this package has built-in type declarations

1.0.1-beta.87 • Public • Published

Vue 3 + TypeScript + Vite + Storybook

This template should help get you started developing with Vue 3 and TypeScript in Vite. The template uses Vue 3 <script setup> SFCs, check out the script setup docs to learn more.

Recommended IDE Setup

Type Support For .vue Imports in TS

Since TypeScript cannot handle type information for .vue imports, they are shimmed to be a generic Vue component type by default. In most cases this is fine if you don't really care about component prop types outside of templates. However, if you wish to get actual prop types in .vue imports (for example to get props validation when using manual h(...) calls), you can enable Volar's Take Over mode by following these steps:

  1. Run Extensions: Show Built-in Extensions from VS Code's command palette, look for TypeScript and JavaScript Language Features, then right click and select Disable (Workspace). By default, Take Over mode will enable itself if the default TypeScript extension is disabled.

  2. Reload the VS Code window by running Developer: Reload Window from the command palette.

You can learn more about Take Over mode here.

vueca

VueCA is a basic component and functions library to be mostly compatible with Viva con Aguas Base-Frontend-Template

Custom Tables & Pagination

The template supports a pagination composable for usage with the build in component <CustomTable>

Usage of pagination

In <script setup> you can create your pagination and set it up

  1. Initialize pagination and set data
// Import usePagination from vueca and init pagination in the component
import { usePagination } from '@vivaconagua/vueca';
const pagination = usePagination();

// 1. Local data source: Import your data array in the component
import data from  '@/data/example.json';
pagination.setList(dummy);

// 2. external data source: Import store and read data in the view
import { useExampleStore } from  '@/stores/ExampleStore';
const store = useExampleStore();
store.list();

// 2.1 Data is shown in the component
import { useExampleStore } from  '@/stores/ExampleStore';
const store = useExampleStore();
watch(
	() =>  store.list,
	(val, nVal) => {
		pagination.setList(store.list);
	},
	{ deep: true }
);
  1. Define search and filter Pagination supports filtering and searching in the table, therefore you need to define on which fields the search and filters should apply.

2.1. Define check for empty search and possible filtering to check if anything need to be applied

const emptyFilter = computed(() => {
	return pagination.state.search == '' &&
		pagination.state.filter.roleList.length == 0;
});

2.2. Define filter function to define, how the filters should be applied

pagination.state.filterCallback = (value, index) => {
	// If the filter is empty, everything is fine
	if (emptyFilter.value) {
		return true;
	}

	// Apply defined filter (e.g. find array of strings in array of strings
	if (pagination.state.filter.roleList.length > 0 &&
		(!value.roles || !value.roles.find((el) => pagination.state.filter.roleList.includes(el)))) {
		return false;
	}
	// Filter for the current value of row.name etc.
	return value.name?.toLowerCase().indexOf(pagination.state.search.toLowerCase()) > -1;
};

2.3. Apply default filter

pagination.filter({ roleList: [] });

Usage of CustomTable with pagination

To use the pagination in the component, the pagination must be applied to da CustomTable component. You therefore define the slots colspan (slot embedded in colgroup), desktop-filter (slot embedded in div), desktop-header (slot embedded in td), desktop-content (slot embedded in tbody), mobile-filter (slot embedded in tr), mobile-header (slot embedded in div) andmobile-content (slot embedded in tbody)

Defining desktop table
<CustomTable :pagination="pagination" :colspan="2", :labels="labels">
	<template v-slot:colspan>
		<col width="10%" />
		<col width="90%" />
	</template>

	<template v-slot:desktop-filter>
		<h2>Roles:</h2>
		<Checkbox id="admin" label="Administrator" v-model="pagination.state.filter.roleList"/>
		<Checkbox id="employee" label="Employee" v-model="pagination.state.filter.roleList"/>
	</template>

	<template v-slot:desktop-header>
		<th class="CustomTable__cell sortable" @click="pagination.sort('firstName')">
			<label> Firstname &varr;</label>
		</th>
		<th class="CustomTable__cell sortable" @click="pagination.sort('lastName')">
			<label> Lastame &varr;</label>
		</th>
		<th class="CustomTable__cell">
			<label>roles</label>
		</th>
	</template>

	<template v-slot:desktop-content>
		<tr class="CustomTable__row" v-for="(res, index) in pagination.getFilteredList()" :key="index">
			<td class="CustomTable__cell"><label> {{ res.firstName }} </label></td>
			<td class="CustomTable__cell"><label> {{ res.lastName }} </label></td>
			<td class="CustomTable__cell"><label> {{ res.roles }} </label></td>
		</tr>
	</template>
</CustomTable>
Defining mobile table
[<CustomTable :pagination="pagination" :colspan="2", :labels="labels"> ....]
	<template v-slot:mobile-filter>
		<h2>Roles:</h2>
		<Checkbox label="admin" id="admin" v-model="pagination.state.filter.roleList"/>
		<Checkbox label="employee" id="employee" v-model="pagination.state.filter.roleList"/>
	</template>
	<template v-slot:mobile-header>
		<div class="align-left sortable" @click="pagination.sort('firstName')">First name</div>
		<div class="align-right sortable" @click="pagination.sort('lastName')">Last name</div>
	</template>
	<template v-slot:mobile-content>
		<tr class="CustomTable__row" v-for="(res, index) in pagination.getFilteredList()" :key="index">
			<td class="vca-table-cell">
				<Column>
					<Row>
						<div class="align-left CustomTable__index"><span class="bold">{{ res.firstName }}</span></div>
						<div class="align-right CustomTable__index">{{ res.lastName }}</div>
					</Row>
					<Row>
						<div class="align-left" v-if="res.roles"> {{ res.roles.join(', ') }} </div>
					</Row>
				</Column>
			</td>
		</tr>
	</template>
[</CustomTable>]

Labels of the table

The prop labelsof the CustomTable needs to be filled for labelling.

labels: {
	search:  'Search for name',
	page_no_results:  'No results',
	page_label:  'Page',
	page_size:  'Per page',
	page_first:  'Show first',
	page_prev:  'Show previous',
	page_next:  'Show next',
	page_last:  'Show last',
},

Best practices

Sorting

You can call the pagination.sort(cell: string) function to sort your list. It takes the the name of the field as a parameter which should be sorted at. You can also give the name of nested parameter, e.g. pagination.sort('profile.address.country')

Apply translastions in filterCallback

You can add additional information or manipulate data in the filterCallback and then access it in the table. E.g.

pagination.state.filterCallback = (value, index) => {
	value.myIndex = index;
	value.translated = t(value.untranslated);
	value.short = value.long.substring(0, 100);
	// ...
}

Payment Elements (Stripe / Paypal)

You can use the integrated payment elements <StripePayment> and <PaypalButton> when you have some API that can handle and secure the payment process: https://github.com/Viva-con-Agua/donation-backend

The elements will handle requests to the backend to automatically create payments and then purchase those payments with the corresponding payment provider.

Currently implemented are somponents for Stripe IBAN, Stripe CreditCard and Paypal. You can trigger one time payments as well as subscriptions.

Setting up the environment for development

Storybook needs some variables for testing the payment elements.

STORYBOOK_VUECA_PAYMENT_FORM=
STORYBOOK_VUECA_STRIPE_KEY=
STORYBOOK_VUECA_STRIPE_PRODUCT=
STORYBOOK_VUECA_PAYPAL_KEY=
STORYBOOK_VUECA_PAYPAL_SANDBOX=
STORYBOOK_VUECA_PAYPAL_PRODUCT=

Usage of payment elements

You can just import the element and use it with the required props

Component: StripePayment

Usage
<script setup>
	import SepaElement from '@vivaconagua/vueca';
</script
<template>
	<StripePayment v-bind="args" />
</template>
Properties
Property Description Type Required Default
stripeKey Stripe public key string true -
billingDetails Object containing email:string and name:string PaymentBillingDetails true -
url URL of the payment backend string true -
paymentDetails Object containing informations about the payment and the customer: money:Amount, contact:PaymentCreateContact, donation_form_id:string, country:string, publish:string PaymentCreate true -
name Name of the paymenttype defined to use in the Backend API PaymentNameEnum true -
productId ID Of the stripe product string false ''
subscription Subscription (true) or single payment (false) boolean false false
cycles Number of default cycles until the subscription automatically ends number false 0
interval Interval of the subscription (PaymentIntervalEnum.ANNUAL, PaymentIntervalEnum.MONTHLY) PaymentIntervalEnum false PaymentIntervalEnum.ANNUAL
type Type of the payment element from stripe (PaymentStripeEnum.IBAN, PaymentStripeEnum.CARD) PaymentStripeEnum false PaymmentStripeEnum.IBAN
terms Object containing informations about the terms. If defined, the checkbox beneath the Stripe element will appear and needs to be checked to process with the payment. Therefore the object needs value:boolean, label:string, errorMsg:string DefaultTerms false undefined
locale Locale which should be used as default for e.g. placeholder in the iban field StripePaymentLocale false 'de-DE'
disabled Whether element is diasbled or boolean false false
rules Vuelidate rules that should be applied Validation false null
class Additional classes string false ''
label Label for the field string false ''
errorMsg Error message that should be shown when data is invalid string false ''
staticLabel Show label as static label (true) or as top label (false) boolean false ''
Events
Event Description
success Fires when payment or subscription is successfully processed
error Fires when a payment or subscription could not be processed
terms fires when terms checkbox changes its value
valid fires whenever an element gets validated and all validations are fine
invalid fires whenever an element gets validated and not all validations are fine
Exposes

validate = async () => void // Emits valid or invalid purchase = async () => void // Emits success or error payment:Payment // Holds information about the payment if needed

Component: PaypalButton

Usage
<script setup>
	import PaypalButton from '@vivaconagua/vueca';
</script
<template>
	<PaypalButton v-bind="args" />
</template>
Properties
Property Description Type Required Default
paypalKey Paypal client id string true -
billingDetails Object containing email:string and name:string PaymentBillingDetails true -
url URL of the payment backend string true -
paymentDetails Object containing informations about the payment and the customer: money:Amount, contact:PaymentCreateContact, donation_form_id:string, country:string, publish:string PaymentCreate true -
client Client credentials for paypal PaypalClient true -
name Name of the paymenttype defined to use in the Backend API PaymentNameEnum false PaymentNamesEnum.PAYPAL
productId ID Of the paypal product string false ''
subscription Subscription (true) or single payment (false) boolean false false
cycles Number of default cycles until the subscription automatically ends number false 0
interval Interval of the subscription (PaymentIntervalEnum.ANNUAL, PaymentIntervalEnum.MONTHLY) PaymentIntervalEnum false PaymentIntervalEnum.ANNUAL
locale Locale which should be used as default for e.g. placeholder in the iban field string false 'de_DE'
disabled Whether element is diasbled or boolean false false
class Additional classes string false ''
label Label for the field string false ''
errorMsg Error message that should be shown when data is invalid string false ''
staticLabel Show label as static label (true) or as top label (false) boolean false ''
Events
Event Description
success Fires when payment or subscription is successfully processed
error Fires when a payment or subscription could not be processed
cancel fires when the user cancels the process
valid fires whenever user starts the process and
invalid fires whenever user starts the process and button is disabled
Exposes

payment:Payment // Holds information about the payment if needed

Full example

<template>
	<StripePayment ref="ibanElement" v-bind="ibanPayment" />
	<StripePayment ref="cardElement" v-bind="cardPayment" />
	<button @click="purchase">Checkout</button>

	<PaypalButton ref="paypalElement" v-bind="paypalPayment" />
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { PaymentNamesEnum, PaymentStripeEnum } from '@types/vivaconagua/vueca';
import { StripePayment, PaypalButton } from '@vivaconagua/vueca';

const  paymentType = ref('paypal');
const  ibanElement = ref();
const  cardElement = ref();
const  paypalElement = ref();

const  purchase = async () => {
	switch (paymentType.value) {
		case  PaymentNamesEnum.CARD:
			cardElement.value.purchase();
			break;
		case  PaymentNamesEnum.SEPA:
			const  sepaValid = await  ibanElement.value.validate();
			if (sepaValid) {
				ibanElement.value.purchase();
			}
			break;
		case  PaymentNamesEnum.PAYPAL:
			break;
	}
};

// Example data for a payment
const  paymentDetails = reactive({
	money: {
		amount:  1000,
		currency:  'EUR',
	},
	contact: {
		first_name:  'UserFirst',
		last_name:  'UserLast',
		email:  'tk_test@vivaconagua.org',
	},
	country:  'DE',
	donation_form_id:  '',
	publish:  'false',
});

// Example data for billing
const  billingDetails = reactive({
	email:  'tk_test@vivaconagua.org',
	name:  'UserFirst UserLast',
});

// Example data for payment elements
const  terms = {
	label:  'Bitte bestätige',
};
const  cardPayment = {
	stripeKey:  '',
	name:  PaymentNamesEnum.CARD,
	type:  PaymentStripeEnum.CARD,
	url:  import.meta.env.STORYBOOK_VUECA_PAYMENT_BACKEND,
	billingDetails,
	paymentDetails,
};

const  ibanPayment = {
	stripeKey:  '',
	name:  PaymentNamesEnum.SEPA,
	type:  PaymentStripeEnum.IBAN,
	url:  import.meta.env.STORYBOOK_VUECA_PAYMENT_BACKEND,
	billingDetails,
	paymentDetails,
	terms,
};

const  paypalPayment = {
	paypalKey:  '',
	client: {
		credentials: {
			sandbox:  '',
		},
	},
	name:  PaymentNamesEnum.PAYPAL,
	url:  import.meta.env.STORYBOOK_VUECA_PAYMENT_BACKEND,
	billingDetails,
	paymentDetails,
};
</script>

Readme

Keywords

none

Package Sidebar

Install

npm i @vivaconagua/vueca

Weekly Downloads

27

Version

1.0.1-beta.87

License

none

Unpacked Size

14.8 MB

Total Files

20

Last publish

Collaborators

  • geschox
  • ixisio
  • sandlewood
  • johannsell
  • tobiaskaestle
  • deinelieblings