FastComments.com

Add Comments to Your SolidJS App

Это официальная библиотека SolidJS для FastComments.

Встраивайте виджеты живых комментариев, чата и обзоров в ваше приложение на SolidJS.

Репозиторий

Просмотреть на GitHub


Установка Internal Link

npm install fastcomments-solidjs

Использование Internal Link

import { FastCommentsCommentWidget } from 'fastcomments-solidjs';

export default function App() {
  return <FastCommentsCommentWidget tenantId="demo" urlId="some-page-id" />;
}

Реагирование на изменения конфигурации (императивный обработчик) Internal Link

Solid does not automatically track deep mutations on arbitrary objects, so config changes after the first render must be pushed explicitly. Every widget accepts an apiRef that returns a handle; call handle.update(partial) from a createEffect to drive reactivity:

import { createEffect, createSignal } from 'solid-js';
import { FastCommentsCommentWidget, type FastCommentsCommentWidgetHandle } from 'fastcomments-solidjs';

export default function Paginated() {
  const [page, setPage] = createSignal(0);
  let handle: FastCommentsCommentWidgetHandle | undefined;
  createEffect(() => handle?.update({ urlId: `product-${page()}` }));

  return (
    <>
      <button onClick={() => setPage(page() + 1)}>next</button>
      <FastCommentsCommentWidget
        apiRef={(h) => (handle = h)}
        tenantId="demo"
        urlId={`product-${page()}`}
      />
    </>
  );
}

update() is safe to call at any time:

  • Before the script has loaded: the partial is stashed and applied at init.
  • During an async init (reviews-summary, user-activity-feed): the partial is queued and applied when the callback resolves.
  • After init: it forwards straight to the live widget's .update() method.

Императивный API handle

interface WidgetHandle<Config> {
  getInstance: () => WidgetInstance | null;   // последний живой экземпляр (или null до монтирования)
  onInstance: (cb: (instance: WidgetInstance) => void) => void; // вызывается один раз, когда экземпляр готов
  update: (partial: Partial<Config>) => void; // объединяет и отправляет конфигурацию
}

Use getInstance() for imperative actions that aren't covered by .update(), e.g. openProfile:

const openProfile = () =>
  (handle?.getInstance() as { openProfile?: (o: { userId: string }) => void } | null)
    ?.openProfile?.({ userId: 'demo' });

Компоненты Internal Link


Каждый виджет из fastcomments-react доступен под тем же именем:

Компонент Тип handle Загружаемый виджет
FastCommentsCommentWidget FastCommentsCommentWidgetHandle Флагманский виджет живых комментариев
FastCommentsCommentCountWidget FastCommentsCommentCountWidgetHandle Инлайн-бейдж с количеством комментариев
FastCommentsLiveChatWidget FastCommentsLiveChatWidgetHandle Потоковый виджет живого чата
FastCommentsCollabChatWidget FastCommentsCollabChatWidgetHandle Совместный чат, привязанный к тексту
FastCommentsImageChatWidget FastCommentsImageChatWidgetHandle Комментарии по регионам изображения
FastCommentsRecentCommentsWidget FastCommentsRecentCommentsWidgetHandle Лента последних комментариев
FastCommentsRecentDiscussionsWidget FastCommentsRecentDiscussionsWidgetHandle Лента последних обсуждений
FastCommentsReviewsSummaryWidget FastCommentsReviewsSummaryWidgetHandle Сводка по звездному рейтингу
FastCommentsTopPagesWidget FastCommentsTopPagesWidgetHandle Рейтинг страниц по количеству комментариев
FastCommentsUserActivityFeedWidget FastCommentsUserActivityFeedWidgetHandle Хронология активности пользователя

Виджеты, которые монтируются в существующий элемент

FastCommentsCollabChatWidget и FastCommentsImageChatWidget монтируются в элемент, переданный вызывающим. Передайте accessor targetRef, который возвращает элемент после монтирования:

import { FastCommentsImageChatWidget } from 'fastcomments-solidjs';

export default function ImageChat() {
  let img: HTMLImageElement | undefined;
  return (
    <>
      <img ref={img} src="/screenshot.png" alt="" />
      <FastCommentsImageChatWidget
        tenantId="demo"
        urlId="my-image"
        targetRef={() => img}
      />
    </>
  );
}

Регионы

Укажите region="eu", чтобы маршрутизировать трафик виджета через кластер ЕС.

Примеры Internal Link


Полное демонстрационное приложение находится в examples/example-showcase/. Оно дублирует демонстрацию React и охватывает каждый виджет, а также распространённые сценарии (тёмная тема, пагинация, SSO, колбэки).

cd examples/example-showcase
npm install
npm run dev

Сборка Internal Link

npm install
npm run build       # library -> dist/
npm test            # vitest smoke test
npm run build:demo  # showcase -> demo-dist/

Нужна помощь?

Если вы столкнулись с проблемами или у вас есть вопросы по библиотеке SolidJS, пожалуйста:

Как внести вклад

Вклады приветствуются! Пожалуйста, посетите репозиторий на GitHub для получения руководства по внесению вклада.