All files / core/blong-gogo/src/adapter/server/viber keyboard.ts

100% Statements 55/55
81.81% Branches 9/11
100% Functions 3/3
100% Lines 55/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 3x 3x 6x 6x 6x 6x 6x 6x 3x 1x 1x 1x 2x 1x 1x 1x 1x  
import type {IChatPrompt} from '@feasibleone/blong/types';
import {library} from '@feasibleone/blong/types';
 
import {chatPromptActionId} from '../../../chatActions.ts';
 
/**
 * The keyboard a canonical prompt becomes.
 *
 * Viber's richest interactive element is a keyboard of reply buttons: the button's `ActionBody` comes
 * back as the text of the next message, which is what lets an answer identify its question. There is
 * no checkbox and no form, so a multiple choice has no rendering here and the caller is told so
 * (`@@D-678`).
 */
const truncate = (value: string, max: number): string =>
    value.length <= max ? value : value.slice(0, max - 1) + '…';
 
export interface IViberButton {
    Columns: number;
    Rows: number;
    Text: string;
    ActionType: 'reply';
    ActionBody: string;
}
 
export interface IViberKeyboard {
    Type: 'keyboard';
    DefaultHeight: boolean;
    Buttons: IViberButton[];
}
 
/** The buttons a choice or a confirmation is answered with. */
export const viberPromptButtons = (prompt: IChatPrompt): IViberButton[] => {
    const options =
        prompt.kind === 'confirm'
            ? [
                  {value: 'yes', label: 'Yes'},
                  {value: 'no', label: 'No'},
              ]
            : (prompt.options ?? []);
    return options.map(option => ({
        Columns: 6,
        Rows: 1,
        Text: truncate(option.label, 30),
        ActionType: 'reply',
        ActionBody: chatPromptActionId(prompt.promptId, option.value),
    }));
};
 
/** The keyboard a message carries, or nothing when the question is answered by typing. */
export const viberPromptKeyboard = (prompt: IChatPrompt): IViberKeyboard | undefined =>
    prompt.kind === 'choice' || prompt.kind === 'confirm'
        ? {Type: 'keyboard', DefaultHeight: false, Buttons: viberPromptButtons(prompt)}
        : undefined;
 
export default library(() => ({viberPromptButtons, viberPromptKeyboard}));