Есть ли способ дать отступы столбцов адаптивной карте - Adaptive MS BOT

Я использую адаптивную карту для отображения динамического содержимого в таблице с помощью пакета шаблонов адаптивных карт.

Мне приходилось настраивать его, но один столбец все еще отказывается встать на место, в столбце всегда будет больше содержимого, чем в других. Таким образом, он выпадает из строк, поэтому таблица расширяется и выглядит некрасиво. [! [Введите здесь описание изображения] [1]] [1]

async testTableData(context) {
var tablePayLoad = {
  $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
  "type": "AdaptiveCard",
  "version": "1.0",
  "body": [
    {
      "type": "TextBlock",
      "weight": "bolder",
      "size": "Medium",
      "text": "Details",
      "horizontalAlignment": "left",
      "separator": true,
    },
    //Databody
    {
      "type": "ColumnSet",
      "separator": true,
      "bleed": true,
      "spacing": "Padding",
      "columns": [
        //Name
        {
          "type": "Column",
          "separator": true,

          "items": [
            {
              "type": "TextBlock",
              "weight": "bolder",
              "size": "small",
              "text": "Name",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              "separator": true,
              "wrap": true,
              "text": "${Name}",
              "size": "small",
              "horizontalAlignment": "center",
            },
          ],
        },
        //Mobile NO
        {
          "type": "Column",
          "separator": true,

          "items": [
            {
              "type": "TextBlock",
              "weight": "bolder",
              "size": "small",
              "text": "Mobile No",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              "separator": true,
              "wrap": true,
              "text": "${MobileNo}",
              "size": "small",
              "horizontalAlignment": "center",
            },
          ],
        },
        //Email Address
        {
          "type": "Column",
          "separator": true,

          "items": [
            {
              "type": "TextBlock",
              "weight": "bolder",
              "size": "small",
              "text": "Email",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              "separator": true,
              "wrap": true,
              "text": "${Email}",
              "size": "small",
              "horizontalAlignment": "center",
            },
          ],
        },
        //DOB
        {
          "type": "Column",
          "separator": true,
          "width": "auto",
          "items": [
            {
              "type": "TextBlock",
              "weight": "bolder",
              "size": "small",
              "text": "D.O.B",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              "separator": true,
              "wrap": true,
              "text": "${DOB}",
              "size": "small",
              "horizontalAlignment": "center",
            },
          ],
        },

        //House Address
        {
          "type": "Column",
          "separator": true,

          "bleed": true,
          "items": [
            {
              "type": "TextBlock",
              "weight": "bolder",
              "size": "small",
              "text": "Address",
              horizontalAlignment: "center",
            },
            {
              "type": "TextBlock",
              "separator": true,
              wrap: true,
              "size": "small",
              "text": "${HouseAddress}",
              horizontalAlignment: "center",
            },
          ],
        },
        //Location
        {
          "type": "Column",
          "separator": true,

          "bleed": true,
          "items": [
            {
              "type": "TextBlock",
              "weight": "bolder",
              "size": "small",
              "text": "Branch",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              "separator": true,
              "wrap": true,
              "size": "small",
              "horizontalAlignment": "center",
              "text": "${Location}",
            },
          ],
        },
      ],
    },

    {
      "type": "TextBlock",
      "weight": "bolder",
      "size": "Medium",
      "text": "Trans.",
      "horizontalAlignment": "left",
      "spacing": "extraLarge",
      "separator": true,
    },

    //Trans.
    {
      "type": "ColumnSet",
      "separator": true,
      "bleed": true,
      "spacing": "Padding",
      "columns": [
        //Amount
        {
          "type": "Column",
          "separator": true,
          "width": "auto",
          "items": [
            {
              "type": "TextBlock",
              "size": "small",
              "weight": "bolder",
              "text": "Amount",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              $data: "${Trans}",
              "separator": true,
              "text": "${Amount}",
              "size": "small",
              "horizontalAlignment": "center",
              "spacing": "ExtraLarge",
            },
          ],
        },
        //Type
        {
          "type": "Column",
          "width": "auto",
          "separator": true,

          "items": [
            {
              "type": "TextBlock",
              "size": "small",
              "weight": "bolder",
              "text": "Type",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              $data: "${Trans}",
              "separator": true,
              "text": "${Type}",
              "size": "small",
              "horizontalAlignment": "center",
              "spacing": "ExtraLarge",
            },
          ],
        },
        //Currency
        {
          "type": "Column",
          "width": "auto",
          "separator": true,

          "items": [
            {
              "type": "TextBlock",
              "size": "small",
              "weight": "bolder",
              "horizontalAlignment": "center",
              "text": "Currency",
            },
            {
              "type": "TextBlock",
              $data: "${Trans}",
              "separator": true,
              "size": "small",
              "wrap": true,
              "text": "${Currency}",
              "horizontalAlignment": "center",
              "spacing": "ExtraLarge",
            },
          ],
        },
        //Date
        {
          "type": "Column",
          //   "bleed": true,
          //   width: "auto",

          "separator": true,

          "items": [
            {
              "type": "TextBlock",
              "size": "small",
              "text": "Date",
              "weight": "bolder",
              "horizontalAlignment": "center",
              "wrap": true,
            },
            {
              "type": "TextBlock",
              $data: "${Trans}",
              "separator": true,
              "wrap": true,
              "text": "${Date}",
              "horizontalAlignment": "center",
              "size": "small",
              "spacing": "ExtraLarge",
            },
          ],
        },

        //Comment
        {
          "type": "Column",
          //   width: "stretch",
          "separator": true,
          //   "bleed": true,
          "items": [
            {
              "type": "TextBlock",
              "size": "small",
              "weight": "bolder",
              "text": "Comment",
              "horizontalAlignment": "center",
            },
            {
              "type": "TextBlock",
              $data: "${Trans}",
              "separator": true,
              "size": "small",
              "wrap": true,
              "text": "${Comments}",
              "spacing": "ExtraLarge",
              "horizontalAlignment": "center",
            },
          ],
        },
      ],
    },
  ],
};

// Create a Template instance from the table payload
var template = new ACData.Template(tablePayLoad);

// Expand the template with your `$root` data object.
// This binds it to the data and produces the final Adaptive Card payload

var data = [
  {
    Amount: "6000",
    Type: "C",
    Currency: "NGN",
    Date: "2019-07-19T00:00:00Z",
    Comments: "Just a regular comment here",
  },
  {
    Amount: "6000",
    Type: "C",
    Currency: "NGN",
    Date: "2019-07-19T00:00:00Z",
    Comments: "Just another Comment here",
  },
];
var dob = new Date("1990-05-29T00:00:00Z");

var tableCardPayload = template.expand({
  $root: {
    Name: "JOHN DOE",
    MobileNo: "2349082182323",
    Email: "[email protected]",
    DOB: dob.toLocaleDateString(),
    HouseAddress: "16, Lagos Street, Lagos",
    Location: "Universe",
    Trans: data,
  },
});

const cardToLoad = CardFactory.adaptiveCard(tableCardPayload);

await context
  .sendActivity({ attachments: [cardToLoad] })
  .then()
  .catch((err) => {
    console.log(err);
  });

},


person Folorunso    schedule 27.07.2020    source источник
comment
Если история редактирования содержит чью-то настоящую контактную информацию, вам следует попросить Stack Overflow отредактировать ее для вас. Они уже отклонили мою просьбу, потому что не увидели доказательств того, что контактная информация действительна.   -  person Kyle Delaney    schedule 21.08.2020


Ответы (2)


Чтобы создать подход в стиле таблицы в AdaptiveCards, вам необходимо использовать columnSets. Однако набор столбцов - это то, что есть, всего лишь один набор столбцов, то есть одна строка данных.

Чтобы получить таблицу, вам нужно добавить по одному столбцу для каждой строки, к счастью, шаблон может легко сделать это за нас.

Вам не нужно создавать какие-либо строки вручную, вам просто нужно привязать данные в нужное место. Посмотри на это:

{
"schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.3",
"body": [
    {
        "type": "TextBlock",
        "weight": "Bolder",
        "size": "Medium",
        "text": "Account Details",
        "horizontalAlignment": "left",
        "separator": true
    },
    {
        "type": "ColumnSet",
        "separator": true,
        "bleed": true,
        "spacing": "Padding",
        "columns": [
            {
                "type": "Column",
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "weight": "Bolder",
                        "size": "Small",
                        "text": "Name",
                        "horizontalAlignment": "Center"
                    },
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "wrap": true,
                        "text": "${Name}",
                        "size": "Small",
                        "horizontalAlignment": "Center"
                    }
                ],
                "width": "stretch"
            },
            {
                "type": "Column",
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "weight": "Bolder",
                        "size": "Small",
                        "text": "Mobile No",
                        "horizontalAlignment": "Center"
                    },
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "wrap": true,
                        "text": "${MobileNo}",
                        "size": "Small",
                        "horizontalAlignment": "Center"
                    }
                ],
                "width": "stretch"
            },
            {
                "type": "Column",
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "weight": "Bolder",
                        "size": "Small",
                        "text": "Email",
                        "horizontalAlignment": "Center"
                    },
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "wrap": true,
                        "text": "${Email}",
                        "size": "Small",
                        "horizontalAlignment": "Center"
                    }
                ],
                "width": "stretch"
            },
            {
                "type": "Column",
                "separator": true,
                "width": "auto",
                "items": [
                    {
                        "type": "TextBlock",
                        "weight": "Bolder",
                        "size": "Small",
                        "text": "D.O.B",
                        "horizontalAlignment": "Center"
                    },
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "wrap": true,
                        "text": "${DOB}",
                        "size": "Small",
                        "horizontalAlignment": "Center"
                    }
                ]
            },
            {
                "type": "Column",
                "separator": true,
                "bleed": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "weight": "Bolder",
                        "size": "Small",
                        "text": "Address",
                        "horizontalAlignment": "Center"
                    },
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "wrap": true,
                        "size": "Small",
                        "text": "${HouseAddress}",
                        "horizontalAlignment": "Center"
                    }
                ],
                "width": "stretch"
            },
            {
                "type": "Column",
                "separator": true,
                "bleed": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "weight": "Bolder",
                        "size": "Small",
                        "text": "Branch",
                        "horizontalAlignment": "Center"
                    },
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "wrap": true,
                        "size": "Small",
                        "horizontalAlignment": "Center",
                        "text": "${DomicileBranch}"
                    }
                ],
                "width": "stretch"
            }
        ]
    },
    {
        "type": "TextBlock",
        "weight": "Bolder",
        "size": "Medium",
        "text": "Last Five Transactions",
        "horizontalAlignment": "left",
        "spacing": "ExtraLarge",
        "separator": true
    },
    {
        "type": "ColumnSet",
        "separator": true,
        "bleed": true,
        "spacing": "Padding",
        "columns": [
            {
                "type": "Column",
                "separator": true,
                "width": 20,
                "items": [
                    {
                        "type": "TextBlock",
                        "size": "Small",
                        "weight": "Bolder",
                        "text": "Amount",
                        "horizontalAlignment": "Center"
                    }
                ]
            },
            {
                "type": "Column",
                "width": 10,
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "size": "Small",
                        "weight": "Bolder",
                        "text": "Type",
                        "horizontalAlignment": "Center"
                    }
                ]
            },
            {
                "type": "Column",
                "width": 20,
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "size": "Small",
                        "weight": "Bolder",
                        "horizontalAlignment": "Center",
                        "text": "Currency"
                    }
                ]
            },
            {
                "type": "Column",
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "size": "Small",
                        "text": "Date",
                        "weight": "Bolder",
                        "horizontalAlignment": "Center",
                        "wrap": true
                    }
                ],
                "width": 20
            },
            {
                "type": "Column",
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "size": "Small",
                        "weight": "Bolder",
                        "text": "Remarks",
                        "horizontalAlignment": "Center"
                    }
                ],
                "width": 30
            }
        ]
    },
    {
        "type": "ColumnSet",
        "separator": true,
        "bleed": true,
        "spacing": "Padding",
        "$data": "${lastFiveTrans}",
        "columns": [
            {
                "type": "Column",
                "separator": true,
                "width": 20,
                "items": [
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "text": "${Amount}",
                        "size": "Small",
                        "horizontalAlignment": "Center",
                        "spacing": "ExtraLarge"
                    }
                ]
            },
            {
                "type": "Column",
                "width": 10,
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "separator": true,
                        "text": "${TransactionType}",
                        "size": "Small",
                        "horizontalAlignment": "Center",
                        "spacing": "ExtraLarge"
                    }
                ]
            },
            {
                "type": "Column",
                "width": 20,
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "text": "${Currency}",
                        "size": "Small",
                        "horizontalAlignment": "Center",
                        "spacing": "ExtraLarge"
                    }
                ]
            },
            {
                "type": "Column",
                "width": 20,
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "text": "${TransactionDate}",
                        "size": "Small",
                        "horizontalAlignment": "Center",
                        "spacing": "ExtraLarge"
                    }
                ]
            },
            {
                "type": "Column",
                "width": 30,
                "separator": true,
                "items": [
                    {
                        "type": "TextBlock",
                        "text": "${Remarks}",
                        "size": "Small",
                        "horizontalAlignment": "Center",
                        "spacing": "ExtraLarge"
                    }
                ]
            }
        ]
    }
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
}

Это должно делать то, что вы хотите. У вас тоже были разные мелкие проблемы. При использовании свойства $ data необходимо использовать его только один раз для элемента, который вы хотите повторить. В вашем случае вы снова и снова повторяли данные в одном и том же столбце. Отступы, автоматический интервал и т. Д. Работают правильно только тогда, когда столбцы сохраняют свой размер пропорционально другим элементам.

Вкратце: создайте таблицу с несколькими наборами столбцов

  • Columnset1 - ›Заголовки таблиц
  • Columnset2-N - ›Строки таблицы
  • Columnset3 - ›Нижние колонтитулы таблицы, если они вам нужны

Чтобы таблица выглядела правильно, вам нужно убедиться, что все столбцы от заголовка до данных имеют одинаковую ширину, что проще всего сделать с шириной в пикселях или с взвешиванием.

person Tim Cadenbach    schedule 12.08.2020
comment
Работает нормально, и я узнал кое-что новое. Но что мне делать, если данные, которые я пытаюсь перебрать в таблицу, велики? для данных среднего размера работает нормально, но при большом размере данных происходит сбой с ошибкой 413 RestError: Message size too large. - person Folorunso; 12.08.2020
comment
Вам придется отправить несколько карточек. Есть ограничение на размер карты около 25 КБ. - person Tim Cadenbach; 12.08.2020
comment
Bot Framework не поддерживает адаптивную карту версии 1.3. Пожалуйста, замените 1.3 на 1.2 - person Kokul Jose; 19.08.2020
comment
Bot Framework как таковой поддерживает любые типы карт. Некоторые хосты еще не поддерживают 1.3 (например, MS Teams. WebChat поддерживает 1.3) - person Tim Cadenbach; 19.08.2020

Я убедился, что использование строк вместо столбцов решит вашу проблему. Это означает, что вместо одного набора столбцов с множеством элементов в каждом столбце у вас будет много наборов столбцов с одним элементом в каждом столбце. Каждый набор столбцов будет служить строкой, и все они будут располагаться друг над другом.

Я написал для вас функцию, которая преобразует столбцы в строки. Вы можете использовать это или можете внести изменения в свою карту вручную. Вот код:

async function sendCard(card) {
    await turnContext.sendActivity(
        MessageFactory.attachment(CardFactory.adaptiveCard(card))
    );
}

function makeRows(columnSet) {
    const rows = [];

    if (columnSet.columns.length) {
        const numRows = columnSet.columns[0].items.length;
        for (let rowIndex = 0; rowIndex < numRows; rowIndex++) {
            const row = Object.assign({}, columnSet);
            row.columns = [];

            for (const column of columnSet.columns) {
                const item = column.items[rowIndex];
                const rowColumn = Object.assign({}, column);
                //item.wrap = true;
                rowColumn.items = [item];
                row.columns.push(rowColumn);
            }

            rows.push(row);
        }
    } else {
        rows.push(columnSet);
    }

    return rows;
}

function replaceColumnsWithRows(body) {
    for (let index = body.length - 1; index > -1; index--) {
        const element = body[index];
        if (element.type == "ColumnSet") {
            const rows = makeRows(element);
            body.splice(index, 1, ...rows);
        }
    }
}

var tablePayLoad = {
    $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
    type: "AdaptiveCard",
    // Your template
};

// Create a Template instance from the table payload
var template = new ACData.Template(tablePayLoad);

// Expand the template with your `$root` data object.
// This binds it to the data and produces the final Adaptive Card payload

var tableCardPayload = template.expand({
    $root: {
        // Your data
    },
});

await sendCard(tableCardPayload);

replaceColumnsWithRows(tableCardPayload.body);

await sendCard(tableCardPayload);
person Kyle Delaney    schedule 11.08.2020
comment
Работает нормально, но что мне делать, если данные, которые я пытаюсь перебрать в таблицу, велики? для данных среднего размера он работает нормально, но как только данные становятся большими, происходит сбой с ошибкой 413 RestError: слишком большой размер сообщения. - person Folorunso; 12.08.2020
comment
Пожалуйста, используйте комментарии, чтобы попросить разъяснений по поводу этого конкретного ответа на этот конкретный вопрос. Если ваши сообщения слишком большие, это не связано с этим вопросом, и вы должны спросить, как решить это в новом вопросе. - person Kyle Delaney; 12.08.2020
comment
Хорошо, спасибо. - person Folorunso; 13.08.2020