API demoNext.js

Try this

  1. Open Ben, the customer, in another window Open as Ben
  2. As Cara, mark the order shipped
  3. As Ben, call Ann from the list of who is in the shop

This shop is yours until Thursday 06:25 PM. Send a window link to a colleague to share it.

Order #1042 · Ben

Two ceramic mugs

  1. Placed
  2. Packed
  3. Shipped
  4. Delivered
Mark as
Timeline
    See the code
    Serverlib/realtime.ts
    // The room of an order: its customer and the shop staff. The last 20 updates kept, which the page shows as its timeline.
    realtime.room('order:{id}', { history: 20 }, (user, { id }) => {
        const order = orderOf(id);
        return !!order && (user === order.customer || (isStaff(user) && sameShop(user, order.customer)));
    });
    Serverapp/actions.ts
    export async function setStatus(orderId: number, status: Status, tab?: string) {
        const user = await currentUserId();
        const order = orderOf(orderId);
        if (!order || !isStaff(user) || !sameShop(user, order.customer) || !STATUSES.includes(status)) return;
    
        order.status = status;
        await realtime.to(`order:${order.id}`).except(tab).emit('updated', { id: order.id, status });
        await realtime.toUser(order.customer).emit('notice', { text: `Your order #${order.number} is ${status}.` });
    }
    Pageapp/(shop)/shop.tsx
    useUserEvent('notice', (data: { text: string }) => say(data.text));
    
    // …
    
    const room = useRoom(name, {
        updated: (data: { status: Status }, meta) => changed(data.status, meta.at ?? Date.now()),
    });
    
    // …
    
    // The order updates the room kept, once it is joined.
    useEffect(() => {
        if (room.state !== 'joined' || !room.room) return;
        room.room.history({ limit: 20 }).then((kept) => {
            const updates = kept.events.filter((e) => e.event === 'updated').map((e) => ({ status: (e.data as { status: Status }).status, at: e.at ?? 0 }));
            setTimeline(updates.slice(Math.max(0, updates.map((u) => u.status).lastIndexOf('placed'))));
        }, () => {});
    }, [room.state, room.room]);
    
    // …
    
    const move = async (next: Status) => {
        changed(next, Date.now());
        await setStatus(initial.id, next, rt?.tab); // emitted to everyone else in the room
    };

    Two ceramic mugs

    See the code
    Serverlib/realtime.ts
    // The product page: anyone, signed in or not, and a live count of who is looking.
    realtime.room('product:{id}', { public: true, count: true });
    Pageapp/(shop)/shop.tsx
    const room = useRoom(name);
    const n = room.count ?? 0;
    
    // …
    
    {room.count === null ? ' ' : n > 1 ? `${n} people are looking at this` : 'Only you are looking at this'}

    Live show

    See the code
    Serverlib/realtime.ts
    // The shop live show, show:mugs: Ann presents it, and everyone else watches and writes in its chat, signed in or not.
    realtime.streams('show:{id}', (user, { id }) => {
        const s = shopOfRoom(`show:${id}`);
        if (s === null || !shops().has(s)) return false;
        return person(user)?.shop === s && person(user)?.name === 'Ann' ? 'host' : 'viewer';
    }, { reactions: true });
    Pageapp/(shop)/shop.tsx
    <LiveStream name={room} title="The new mugs" />

    Daily meeting

    Ann, Ben and Cara, with video.

    See the code
    Serverlib/realtime.ts
    // The daily meeting: a group call for everyone in the shop.
    realtime.groupCalls('meeting:{id}', (user, { id }) => person(user)?.shop === (id === 'daily' ? 0 : Number(id)));
    Pageapp/(shop)/shop.tsx
    <GroupCallButton rt={rt} room={room} type="video" title="Daily meeting">
        Join the meeting
    </GroupCallButton>

    Chat

    The chat is between Ann and Ben.

    Members

    A call rings for a member in their own window: open it with Open as to answer.

    See the code
    Serverlib/realtime.ts
    // Calls between two people, support:34:42: the two it names, one of them staff. Either of them may bring more staff in,
    // and the call goes on as a group call: the one adding calls the staff member about it, who takes the call from them.
    realtime.calls('support:{a}:{b}', (user, withUser, { a, b }) => {
        // The two it names, compared as text: a user may be an id of text as well as a number.
        const named = (u: unknown) => [a, b].includes(String(u));
        if (!sameShop(user, withUser, a, b)) return false;
        if (named(user) && named(withUser)) return isStaff(user) || isStaff(withUser);
        return (named(user) && isStaff(withUser)) || (isStaff(user) && named(withUser));
    }, {
        // Whom the call screen offers to add: the shop staff not in the call.
        people: (user, call) => peopleOf(shopOf(user)).filter((p) => p.staff && !call.split(':').slice(1).map(Number).includes(p.id)).map((p) => p.id),
    });
    Pageapp/(shop)/shop.tsx
    {/* A private call to this member, by video or by voice, named by the two of them. */}
    <CallButton rt={rt} to={p.id} call="support:{pair}" type="video" name={p.name} avatar={p.avatar}>
        Video call
    </CallButton>
    <CallButton rt={rt} to={p.id} call="support:{pair}" type="audio" name={p.name} avatar={p.avatar}>
        Voice call
    </CallButton>
    In the shop now (0)
    No users online
    See the code
    Serverlib/realtime.ts
    // Who is in the shop: its people, with their name and role.
    const member = (user: unknown, s: number) => {
        const p = person(user);
        return p?.shop === s ? { info: { name: p.name, role: p.role } } : false;
    };
    realtime.room('shop', { presence: true }, (user) => member(user, 0));
    realtime.room('shop:{s}', { presence: true }, (user, { s }) => member(user, Number(s)));
    Pageapp/(shop)/shop.tsx
    const { online } = useOnline(people.map((p) => p.id));
    
    // …
    
    {here ? <OnlineList rt={rt} room={room} title="In the shop now" call="support:{pair}" type="video" /> : <p className="muted">You stepped out.</p>}

    Webhooks your server got

    None yet. Send a message in the chat: your server hears it by webhook.

      See the code
      Serverlib/realtime.ts
      // The webhooks this server got, sent on to the shop people as they come (below), the last 20 kept.
      realtime.room('webhooks', { history: 20 }, (user) => person(user)?.shop === 0);
      realtime.room('webhooks:{s}', { history: 20 }, (user, { s }) => person(user)?.shop === Number(s));
      
      // …
      
      // What WordPlus Cloud tells this server by webhook (set https://<your server>/api/realtime/webhook on your app page in
      // WordPlus Cloud): a message or reaction from a page, someone coming online, the live show going live … each sent on to
      // its shop webhooks room. A live stream event names its stream (show:mugs) where the others name a room.
      realtime.on('*', async (event) => {
          const room = 'room' in event ? event.room : 'stream' in event ? event.stream : null;
          const s = room ? shopOfRoom(room) : 'user' in event ? shopOf(event.user) : null;
          if (s === null || !shops().has(s) || room?.startsWith('webhooks')) return;
          if (event.type === 'emit' && room === roomsOf(s).chat) keepChat(shops().get(s)!.chat, event);
          const type = event.type === 'emit' ? event.event : event.type;
          const user = 'user' in event ? event.user : 'from' in event ? event.from : null;
          await realtime.to(roomsOf(s).webhooks).emit('webhook', { type, room, user: user ?? null, at: event.at });
      });
      Pageapp/(shop)/shop.tsx
      const room = useRoom(name, { webhook: (w: Webhook, meta) => add({ ...w, at: w.at ?? meta.at }) });
      
      useEffect(() => {
          if (room.state !== 'joined' || !room.room) return;
          room.room.history({ limit: 8 }).then((kept) => {
              setList(kept.events.filter((e) => e.event === 'webhook').map((e) => e.data as Webhook).reverse());
          }, () => {});
      }, [room.state, room.room]);