Skip to content

Commit

Permalink
Moves Operation menu to a higher level. (#817) (#818)
Browse files Browse the repository at this point in the history
* Moves Operation menu to a higher level.

Signed-off-by: Hector Custódio <hector.custodio@zup.com.br>

* Fixes image sample size

Signed-off-by: Hector Custódio <hector.custodio@zup.com.br>
  • Loading branch information
hectorcustodiozup committed Dec 2, 2021
1 parent ca04e2e commit e361c8e
Show file tree
Hide file tree
Showing 18 changed files with 83 additions and 70 deletions.
File renamed without changes.
Expand Up @@ -10,6 +10,7 @@ After you've seen it is possible to make addition, subtraction and other operati

{{< tabs id="T147" >}}
{{% tab name="iOS" %}}
</br>
The registration of an operation on iOS is through `OperationsProvider`protocol, see below:

```swift
Expand Down Expand Up @@ -51,7 +52,7 @@ Done! Your operation can be used now!
{{% /tab %}}

{{% tab name="Android" %}}

</br>
You must the `Operation` interface in order to register a new operation on Android. The example below shows this interface signature


Expand Down Expand Up @@ -122,6 +123,44 @@ class IsValidCPFOperation : Operation {
```
Done! Your operation can be used now!

{{% /tab %}}

{{% tab name="Web" %}}
</br>
Registering custom operations in web apps is pretty straight forward

You first have to create a function receiving any parameters you need and with the logic for your use case.

Let's see an example on how we would create an action to validate a CPF register number, re-using a validation library.
```
import { createBeagleUIService } from '@zup-it/beagle-react'
import { cpf } from 'cpf-cnpj-validator';


function myCustomOperation(cpfInput: string): boolean {
if (!cpfInput) return false
return cpf.isValid(cpfInput)
}


export default createBeagleUIService({
baseUrl: '',
customOperations: {
isValidCpf: myCustomOperation
},
components: {},
})

```

It is as simple as that, the two highlights in the previous code are:
1. Create a custom function receiving the same parameters you intend to send from the JSON
2. Add to your Beagle Service initializer the ``customOperations`` key which will receive a map of ``key:value`` pairs where the key is the name of the custom action and the value is the function you just created.


Done! Your operation can be used now!

{{% /tab %}}
{{< /tabs >}}

Expand All @@ -130,37 +169,6 @@ Done! Your operation can be used now!
See below an example using the `isvalidCpf` operation that was created above, where the text component `Text` will vary according the verification result, if the CPF is valid or not:

{{< tabs id="T148" >}}
{{% tab name="JSON" %}}
<!-- json-playground:customOperation.json
{
"_beagleComponent_" : "beagle:screenComponent",
"navigationBar" : {
"title" : "Custom operation",
"showBackButton" : true
},
"child" : {
"_beagleComponent_" : "beagle:container",
"children" : [ {
"_beagleComponent_" : "beagle:button",
"text" : "CPF atual: @{cpf}",
"onPress" : [ {
"_beagleAction_" : "beagle:setContext",
"contextId" : "cpf",
"value" : "42249625000"
} ]
}, {
"_beagleComponent_" : "beagle:text",
"text" : "@{condition(isValidCpf(cpf), 'cpf is valid', 'cpf is not valid')}"
} ],
"context" : {
"id" : "cpf",
"value" : "00000000000"
}
}
}
-->
{{% playground file="customOperation.json" language="en" %}}
{{% /tab %}}
{{% tab name="Kotlin" %}}
```kotlin
fun screen() = Screen(
Expand All @@ -182,4 +190,6 @@ fun screen() = Screen(
{{% /tab %}}
{{< /tabs >}}

![](/shared/customoperation.gif)
{{< figure src="/shared/customoperation.gif" width="250">}}


File renamed without changes.
File renamed without changes.
File renamed without changes.
Expand Up @@ -6,10 +6,11 @@ description: "Nesta seção, você encontra descrição completa das Custom Oper

---

Depois que você viu que é possível realizar[ **Operações**]({{< ref path="/api/context/operations" lang="pt" >}}) do tipo soma, subtração, etc, utilizando o contexto, você também pode criar a sua própria operação na plataforma que você quiser:
Depois que você viu que é possível realizar[ **Operações**]({{< ref path="/api/operations" lang="pt" >}}) do tipo soma, subtração, etc, utilizando o contexto, você também pode criar a sua própria operação na plataforma que você quiser:

{{< tabs id="T165" >}}
{{% tab name="iOS" %}}
</br>
O registro de uma operação no iOS é feito através de um protocolo chamado `OperationsProvider`, veja abaixo:

```swift
Expand Down Expand Up @@ -51,7 +52,7 @@ Pronto! Sua operação já pode ser utilizada!
{{% /tab %}}

{{% tab name="Android" %}}

</br>
O registro de uma operação no android é feito através de uma interface chamada Operation, veja abaixo:

```java
Expand Down Expand Up @@ -125,47 +126,49 @@ class IsValidCPFOperation : Operation {
Pronto! Sua operação já pode ser utilizada!

{{% /tab %}}
{{< /tabs >}}

## Exemplo
{{% tab name="Web" %}}
</br>
Registrar ações customizadas em aplicações web é uma tarefa bem direta.

Veja abaixo o exemplo utilizando a operação `isValidCpf` que foi criada acima, onde o texto do componente `Text` varia de acordo com o resultado da verificação se o CPF é válido ou não:
Primeiro criamos uma função que recebe os parâmetros que você precisa e com a lógica específica para seu caso de uso.

{{< tabs id="T166" >}}
{{% tab name="JSON" %}}

<!-- json-playground:customOperation.json
{
"_beagleComponent_" : "beagle:screenComponent",
"navigationBar" : {
"title" : "Custom operation",
"showBackButton" : true
},
"child" : {
"_beagleComponent_" : "beagle:container",
"children" : [ {
"_beagleComponent_" : "beagle:button",
"text" : "CPF atual: @{cpf}",
"onPress" : [ {
"_beagleAction_" : "beagle:setContext",
"contextId" : "cpf",
"value" : "42249625000"
} ]
}, {
"_beagleComponent_" : "beagle:text",
"text" : "@{condition(isValidCpf(cpf), 'cpf is valid', 'cpf is not valid')}"
} ],
"context" : {
"id" : "cpf",
"value" : "00000000000"
}
}
Veja um exemplo de como criar uma ação para validar números de CPF, reutilizando uma bibilioteca pronta de validações.

```
import { createBeagleUIService } from '@zup-it/beagle-react'
import { cpf } from 'cpf-cnpj-validator';


function myCustomOperation(cpfInput: string): boolean {
if (!cpfInput) return false
return cpf.isValid(cpfInput)
}
-->

{{% playground file="customOperation.json" language="pt" %}}

export default createBeagleUIService({
baseUrl: '',
customOperations: {
isValidCpf: myCustomOperation
},
components: {},
})

```

É bem simples mesmo, os dois pontos principais do código anterior são:
1. Criar uma função recebendo os mesmos parâmetros que você pretende usar a partir do JSON
2. Adicione ao inicializador do Beagle Service a chave ``customOperations`` que recebe um mapa de pares ``chave:valor`` onde a chave é o nome da ação customizada e o valor é a função que foi criada

Pronto! Sua operação já pode ser utilizada!
{{% /tab %}}
{{< /tabs >}}

## Exemplo

Veja abaixo o exemplo utilizando a operação `isValidCpf` que foi criada acima, onde o texto do componente `Text` varia de acordo com o resultado da verificação se o CPF é válido ou não:

{{< tabs id="T166" >}}
{{% tab name="Kotlin DSL" %}}

```kotlin
Expand All @@ -189,4 +192,4 @@ fun screen() = Screen(
{{% /tab %}}
{{< /tabs >}}

![](/shared/customoperation.gif)
{{< figure src="/shared/customoperation.gif" width="250">}}
File renamed without changes.
File renamed without changes.

0 comments on commit e361c8e

Please sign in to comment.