# 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.

```ts
import { createApp } from "vue";
import { ScreebPlugin } from "@screeb/sdk-vue";
import App from "./App.vue";

createApp(App)
  .use(ScreebPlugin, {
    autoInit: true,
    websiteId: "<YOUR-CHANNEL-ID>",
    userId: "<USER-ID>",
    hooks: {
      version: "1.0.0",
      onReady: (payload) => {
        console.log("Screeb is ready", payload);
      },
      onSurveyCompleted: (payload) => {
        console.log("Survey completed", payload.survey.id, payload.response.items);
      },
    },
  })
  .mount("#app");
```

> [!WARNING]
> The hooks set at initialization reach Screeb only when you also pass a user id or user properties. For an anonymous visitor, pass at least one user property.

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

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

```ts
// Kept in a variable: the start hook types do not declare version, which the SDK requires.
const surveyHooks = {
  version: "1.0.0",
  onSurveyCompleted: (payload: unknown) => {
    console.log("Feedback survey completed", payload);
  },
};
await surveyStart("<SURVEY-ID>", undefined, true, {}, surveyHooks);

const messageHooks = {
  version: "1.0.0",
  onMessageHidden: (payload: unknown) => {
    console.log("Message closed", payload);
  },
};
await messageStart("<MESSAGE-ID>", true, {}, messageHooks);
```

## 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.

```ts
createApp(App)
  .use(ScreebPlugin, {
    autoInit: true,
    websiteId: "<YOUR-CHANNEL-ID>",
    userId: "<USER-ID>",
    hooks: {
      version: "1.0.0",
      onSurveyDisplayAllowed: () => !document.querySelector("dialog[open]"),
      onMessageDisplayAllowed: () => !document.querySelector("dialog[open]"),
    },
  })
  .mount("#app");
```

> [!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               |

## 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 }`.

## Button navigation hooks

A message or tour button can navigate to a URL. Two hooks surround that navigation. Set them at initialization or when you start a survey or message.

| Hook                        | Called when                                                                                                                          |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `onButtonNavigateStarted`   | Right before the navigation. With the `in-page` target the page is about to unload, so this is the last code that runs.              |
| `onButtonNavigateCompleted` | After the navigation. Not called with the `in-page` target, which reloads the page: use `in-page-spa` or `new-tab` when you need it. |

Their payload is `channel`, `user`, `survey`, `response: { id }` and `button: { url, url_target }`, where `url_target` is `"in-page"`, `"in-page-spa"` or `"new-tab"`.

### Single-page apps

The `in-page-spa` target navigates without reloading the page, so the SDK and `onButtonNavigateCompleted` survive it. It detects your router:

- Routers that intercept link clicks (SvelteKit, Astro view transitions, Nuxt) get a real anchor click and navigate with their own state.
- Routers built on the History API (React Router, Angular, Vue Router) get `history.pushState` and a `popstate` event, plus a `hashchange` event in hash mode.

A cross-origin URL always triggers a full navigation.

When your router fits neither case, give Screeb a navigation handler at initialization. It receives the full same-origin URL and performs the navigation. It may return a promise, which Screeb awaits before calling `onButtonNavigateCompleted`.

```ts
createApp(App)
  .use(ScreebPlugin, {
    autoInit: true,
    websiteId: "<YOUR-CHANNEL-ID>",
    spaNavigationHandler: (url) => yourRouter.navigate(url),
  })
  .mount("#app");
```
