#1898: Custom Widgets in Swarmica (Web Plugins)

Отредактирована: 29 дней назад

Description

Swarmica allows you to embed custom applications into the interface on the ticket, article, user account, company, license, and asset screens as web plugins.

A widget, or web plugin, is HTML code that can use data from the screen context—for example, a ticket number or a custom user-account field—in its own logic.

Web plugins can be used to:

  • display a link to a user's CRM account using `user.ext_id`;
  • display part of a user's personal account in an iframe, dynamically adding the account ID to the URL;
  • add a mini-application that reads an article aloud;
  • add a license-key widget to the billing interface.

A web plugin can contain HTML, JavaScript, and CSS, so it can implement almost any frontend application logic.

To enable web-plugin management, update Swarmica to version 6.0.x or later and add the feature flag `ui_widgets`.

Configuring a web plugin

  1. Go to Settings > Integrations > Custom widgets.

  2. Click Create and select the screen where the widget should be displayed.

  3. Configure the widget:

    1. Name — the widget panel title.
    2. Available to — the user roles that can see the widget.
    3. Code — the widget code. See Using dynamic context data.
  4. Click Save and enter an object ID to preview the widget, for example, a ticket number:

  5. Enable the widget and click Save. To change its position, go to Settings > Fields and forms > Screen settings and move it to the required location:

WARNING! Widget code is sent to the browser of every system user who is allowed to see it. DO NOT USE permanent API tokens or other authorization data in widget code if they could provide elevated access to an integrated system.

Using dynamic context data

When the plugin is rendered, its code is processed by the Jinja template engine. The object for which the plugin is displayed is passed into the template context, so you can use any attributes available on that object.

For example, you can use a custom user-account field to generate an iframe URL:

<iframe src="https://my_crm/accounts/{{ user.custom_fields.get_value('CF_UID') }}" ></iframe><p></p>

For more information, see Using context variables.

Plugin examples

The following examples demonstrate what web plugins can do.

Purpose: Make local notes that are not stored on the server while working on a ticket.

Code:

<style>
#notes-widget {
  background: #fff8a6;
  border-radius: 10px;
  padding: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, .15);
}
#notes {
  min-height: 220px;
  max-height: 300px;
  overflow-y: auto;
  outline: none;
  font-family: "Segoe Print", "Comic Sans MS", cursive;
  font-size: 15px;
  line-height: 30px;
  padding: 8px 10px;
  white-space: pre-wrap;
  color: black;
}
#notes:empty::before {
  content: "Write something...";
  color: rgba(0,0,0,.4);
}
#notes::-webkit-scrollbar { display: none; }
#status {
  margin-top: 8px;
  text-align: right;
  font-size: 12px;
  color: #666;
}
</style>

<div id="notes-widget">
  <div id="notes" contenteditable="true"></div>
  <div id="status"></div>
</div>

<script type="module">
const STORAGE_KEY = \`quick-notes:{{ticket.id}}\`
const notes = document.querySelector("#notes")
const status = document.querySelector("#status")
notes.innerHTML = localStorage.getItem(STORAGE_KEY) ?? ""
let saveTimer
let statusTimer

function showStatus(text) {
  status.textContent = text
  clearTimeout(statusTimer)
  statusTimer = setTimeout(() => {
    status.textContent = ""
  }, 1500)
}

function save() {
  localStorage.setItem(STORAGE_KEY, notes.innerHTML)
  showStatus("Saved ✓")
}

notes.addEventListener("input", () => {
  clearTimeout(saveTimer)
  saveTimer = setTimeout(save, 500)
})

notes.addEventListener("keydown", event => {
  if ((event.ctrlKey || event.metaKey) && event.key === "s") {
    event.preventDefault()
    save()
  }
})
</script>

Purpose: Display a counterparty's address on a map.

Code:

<div id="map-widget">
  <input type="text" id="map-query" placeholder="For example: Moscow" />
  <button type="button" id="show-map">GO</button>
  <div id="map-container" style="height:400px"></div>
</div>

<script type="module">
const input = document.querySelector("#map-query")
const button = document.querySelector("#show-map")
const container = document.querySelector("#map-container")

async function renderMap(query) {
  const res = await fetch(
    \`https://nominatim.openstreetmap.org/search?format=json&q=\${encodeURIComponent(query)}\`
  )
  const [place] = await res.json()

  if (!place) {
    container.innerHTML = "<div>Nothing found</div>"
    return
  }

  const lat = Number(place.lat)
  const lon = Number(place.lon)

  container.innerHTML = \`
    <iframe
      width="100%"
      height="100%"
      frameborder="0"
      loading="lazy"
      src="https://www.openstreetmap.org/export/embed.html?bbox=\${lon-0.01},\${lat-0.01},\${lon+0.01},\${lat+0.01}&layer=mapnik&marker=\${lat},\${lon}">
    </iframe>
  \`
}

button.addEventListener("click", () => {
  const query = input.value.trim()
  if (!query) {
    container.innerHTML = "<div>Enter a place</div>"
    return
  }
  renderMap(query)
})

input.addEventListener("keydown", event => {
  if (event.key === "Enter") button.click()
})

renderMap("Moscow")
</script>

Purpose: Help editors check article accessibility.

Code:

<div id="voice-reader-widget">
  <div>Article #{{article.id}}</div>
  <button type="button" id="read-article">🔊 Read</button>
  <button type="button" id="stop-reading">⏹ Stop</button>
</div>

<script type="module">
document.querySelector("#read-article").addEventListener("click", async () => {
  const data = await fetch("/api/articles/{{article.id}}/", {
    headers: {
      Authorization: \`Bearer \${JSON.parse(localStorage.getItem("access"))}\`,
    },
  })

  const article = await data.json()
  const text = (article.body.ru || article.body.en)
    .replace(/!\\[.*?\\]\\(.*?\\)/g, "")
    .replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, "$1")
    .replace(/[#*_>-]/g, "")
    .replace(/\\n+/g, " ")
    .trim()

  const utterance = new SpeechSynthesisUtterance(text)
  utterance.lang = article.body.ru ? "ru-RU" : "en-US"

  speechSynthesis.cancel()
  speechSynthesis.speak(utterance)
})

document.querySelector("#stop-reading").addEventListener("click", () => {
  speechSynthesis.cancel()
})
</script>

Purpose: Perform calculations without leaving the application.

Code:

<div id="calculator-widget">
  <input type="text" id="calculator-input" placeholder="2 + 2" />
  <button type="button" id="calculate">Calculate</button>
  <output id="calculator-result"></output>
</div>

<script type="module">
const input = document.querySelector("#calculator-input")
const button = document.querySelector("#calculate")
const result = document.querySelector("#calculator-result")

button.addEventListener("click", () => {
  try {
    result.textContent = Function(\`"use strict"; return (\${input.value})\`)()
  } catch {
    result.textContent = "Invalid expression"
  }
})
</script>