# Hooks

Run your own code when Screeb is ready, when a survey or message shows, gets an answer or closes, and decide whether it may show at all.

Hooks are callbacks that Screeb calls on lifecycle events: the SDK is ready, a survey or message shows, the user answers a question, a survey closes. Use them to sync your app with Screeb, for example to pause a video while a survey is on screen, or to send a completed survey to your analytics. One hook can also decide whether a survey or message may show.

Every hook is optional. Every hooks object carries a version, `"1.0.0"`, the only one that exists: the SDK rejects hooks without it.

## Set hooks at initialization

Hooks set at initialization apply to every survey and message of the session.

```swift
// Hooks run on a background queue: dispatch UI work to the main queue.
Screeb.initSdk(
    context: nil,
    channelId: "<YOUR-CHANNEL-ID>",
    identity: "<USER-ID>",
    hooks: [
        "version": "1.0.0",
        "onReady": { (payload: Any) -> () in
            print("Screeb is ready \(payload)")
        },
        "onSurveyCompleted": { (payload: Any) -> () in
            print("Survey completed \(payload)")
        }
    ]
)
```

## Set hooks when you start a survey or a message

Hooks passed when you [start a survey](https://developers.screeb.app/sdk-ios/start-survey-programmatically) or [start a message](https://developers.screeb.app/sdk-ios/start-message-programmatically) apply to that survey or message only. They run in addition to the hooks set at initialization, not instead of them.

```swift
Screeb.startSurvey(
    surveyId: "<SURVEY-ID>",
    hooks: [
        "version": "1.0.0",
        "onSurveyCompleted": { (payload: Any) -> () in
            print("Feedback survey completed \(payload)")
        }
    ]
)

Screeb.startMessage(
    messageId: "<MESSAGE-ID>",
    hooks: [
        "version": "1.0.0",
        "onMessageHidden": { (payload: Any) -> () in
            print("Message closed \(payload)")
        }
    ]
)
```

## Decide whether a survey or message shows

`onSurveyDisplayAllowed` and `onMessageDisplayAllowed` run before a survey or message shows. Return `false` to block it, `true` to let it show. Set them at initialization: they are the only hooks that send an answer back, and they are not accepted when you start a survey or message.

```swift
Screeb.initSdk(
    context: nil,
    channelId: "<YOUR-CHANNEL-ID>",
    hooks: [
        "version": "1.0.0",
        // Return false to keep the survey or message hidden.
        "onSurveyDisplayAllowed": { (payload: Any) -> Bool in
            return true
        },
        "onMessageDisplayAllowed": { (payload: Any) -> Bool in
            return true
        }
    ]
)
```

> [!WARNING]
> Answer within 5 seconds. Past that deadline the display check fails and the survey or message does not show. Keep these callbacks fast, avoid network calls, and return `true` early when unsure.

## Available hooks

| Hook                      | Called when                                                               | Where you set it                            |
| ------------------------- | ------------------------------------------------------------------------- | ------------------------------------------- |
| `onReady`                 | The SDK is loaded and initialized                                         | Initialization                              |
| `onSurveyDisplayAllowed`  | A survey is about to show: return whether it may                          | Initialization                              |
| `onMessageDisplayAllowed` | A message is about to show: return whether it may                         | Initialization                              |
| `onSurveyShowed`          | A survey appears on screen, including when it shows again after a reload  | Initialization, survey start                |
| `onSurveyStarted`         | A survey starts                                                           | Initialization, survey start                |
| `onQuestionReplied`       | The user answers a question                                               | Initialization, survey start, message start |
| `onSurveyCompleted`       | The user reaches the end of a survey                                      | Initialization, survey start                |
| `onSurveyHidden`          | A survey leaves the screen, for any reason                                | Initialization, survey start                |
| `onMessageShowed`         | A message appears on screen, including when it shows again after a reload | Initialization, message start               |
| `onMessageStarted`        | A message starts                                                          | Initialization, message start               |
| `onMessageCompleted`      | The user reaches the end of a message                                     | Initialization, message start               |
| `onMessageHidden`         | A message leaves the screen, for any reason                               | Initialization, message start               |

`onAppStoreRatingTriggered` runs when an app store rating question asks for a rating. Set it at initialization or when you start a survey or message.

## Payloads

Every payload carries the channel and the user. Survey hooks add the survey, message hooks add the message, and most of them add the response:

```text
channel   { id: string, type: "widget" | "ios" | "android" }
user      { anonymous_id: string, user_id: string | null }
survey    { id: string, survey_format: "conversationnal" | "cards",
            survey_position: "center-left" | "center-center" | "center-right"
                           | "bottom-left" | "bottom-center" | "bottom-right",
            survey_size: 25 | 50 | 75 | 100 | 125 | 150 }
message   { id: string, message_size: 25 | 50 | 75 | 100 | 125 | 150 }
item      { question: { id: string, title: string, type: "text" | "video", url?: string },
            answer: { replied_at?: string, fields?: field[] } }
field     { type: "string" | "number" | "boolean" | "none" | "time" | "url",
            text?: string, number?: number, boolean?: boolean, time?: string,
            button_url?: string, button_url_target?: "in-page" | "in-page-spa" | "new-tab",
            button_actions?: object[] }
```

`user_id` is null until you identify the user. `survey_format` is spelled `conversationnal`, with two n, in the payloads.

| Hook                                    | Payload                                                                                  |
| --------------------------------------- | ---------------------------------------------------------------------------------------- |
| `onReady`, `onAppStoreRatingTriggered`  | `channel`, `user`                                                                        |
| `onSurveyDisplayAllowed`                | `channel`, `user`, `survey: { id }`, `ai_detection`                                      |
| `onMessageDisplayAllowed`               | `channel`, `user`, `message: { id }`, `ai_detection`                                     |
| `onSurveyStarted`                       | `channel`, `user`, `survey`, `response: { id }`                                          |
| `onSurveyShowed`, `onSurveyCompleted`   | `channel`, `user`, `survey`, `response: { id, items: item[] }`                           |
| `onSurveyHidden`                        | `channel`, `user`, `survey`, `response: { id, items: item[], hide_reason }`              |
| `onMessageStarted`                      | `channel`, `user`, `message`, `response: { id }`                                         |
| `onMessageShowed`, `onMessageCompleted` | `channel`, `user`, `message`, `response: { id, items: item[] }`                          |
| `onMessageHidden`                       | `channel`, `user`, `message`, `response: { id, items: item[], hide_reason }`             |
| `onQuestionReplied`                     | `channel`, `user`, `survey`, `response: { id, status, question, answer, items: item[] }` |

- `hide_reason` and `status` are one of `"displayed"`, `"started"`, `"ended"` (the user reached the end), `"closed"` (the user closed it) or `"interrupted"` (your code or the SDK closed it).
- In `onQuestionReplied`, `question` and `answer` are the last answered item. For a message, the `survey` field holds the message id and its `message_size`.
- `ai_detection` tells whether the visitor looks like an AI agent, or null when unknown: `{ classification: "human" | "likely_human" | "likely_agent" | "agent", confidence_score: number, referrer_ai: string | null, is_ai_referral: boolean }`.
