Components

Toast

A notice in the corner that goes by itself, or when dismissed.

Previews are drawn in the theme you made.

Edit it
tone
scheme
direction

Types #

    import { Schema } from 'effect'
    import { Bundle } from 'foldkit-bundle'
    import { Bundles, Button, Recipes, Toast, ToastSlots } from 'foldkit-mixins-ui'
    import { example } from '../../gallery/example.js'
    
    const Choose = Recipes.Button.style({ tone: 'neutral', variant: 'outline' })
    
    const types = ['default', 'info', 'success', 'warning', 'error'] as const
    const titles = {
      default: 'Event created',
      info: 'A new version is out',
      success: 'Changes saved',
      warning: 'Your session ends in 5 minutes',
      error: 'The file could not be read',
    } as const
    
    // One button per type; the application answers each with the stack's `show`
    // helper. The stack's countdown, hold and swipe are the component's.
    const App = Bundle.compose({}).pipe(
      Bundle.withMessages({ Raised: { type: Schema.Literals(types) } }),
      Bundle.withChild('toasts', Bundles.Toast, { args: { id: 'toasts-types' }, onOut: Bundle.ignore }),
    )
    
    export default example({
      title: 'Types',
      slots: ToastSlots,
      recipe: Recipes.Toast,
      state: App.placements.runtime({
        Model: App.Model,
        initial: {},
        update: App.placements.update((model, { type }) =>
          App.children.toasts.helpers.show({ type, title: titles[type] })(model),
        ),
      }),
      view: ({ style, model, onMessage, h }) =>
        h.div(
          [h.Style({ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' })],
          [
            ...types.map(type =>
              Button.view(
                { label: type, onClick: onMessage(App.Message.Raised({ type })), style: Choose },
                h,
              ),
            ),
            Toast.view(
              {
                model: model.toasts,
                onMessage: message => onMessage(App.Message.GotToastsMessage({ message })),
                label: 'Notifications',
                style,
              },
              h,
            ),
          ],
        ),
    })

    In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

    A promise #

      import { Duration, Effect, Match, Schema } from 'effect'
      import { Bundle } from 'foldkit-bundle'
      import * as Command from 'foldkit/command'
      import { Bundles, Button, Recipes, Spinner, Toast, ToastSlots } from 'foldkit-mixins-ui'
      import { example } from '../../gallery/example.js'
      
      const Primary = Recipes.Button.style({})
      const Ring = Recipes.Spinner.style({})
      
      // A promise toast: raise a loading toast, run the work as a Command, and
      // settle the same toast with its outcome when the work's Message comes back.
      // The id is the stack's own, read before the toast is shown.
      const App = Bundle.compose({}).pipe(
        Bundle.withMessages({ Started: {}, Finished: { id: Schema.String } }),
        Bundle.withChild('toasts', Bundles.Toast, { args: { id: 'uploads' }, onOut: Bundle.ignore }),
      )
      
      const Upload = Command.define('Upload', {
        args: { id: Schema.String },
        messages: [App.Message.Finished],
        execute: ({ id }) =>
          Effect.sleep(Duration.millis(1500)).pipe(Effect.as(App.Message.Finished({ id }))),
      })
      
      export default example({
        title: 'A promise',
        slots: ToastSlots,
        recipe: Recipes.Toast,
        state: App.placements.runtime({
          Model: App.Model,
          initial: {},
          update: App.placements.update((model, message) =>
            Match.valueTags(message, {
              Started: () => {
                const id = Toast.nextId(model.toasts)
                const shown = App.children.toasts.helpers.show({
                  type: 'loading',
                  title: 'Uploading report.pdf…',
                })(model)
                return { model: shown.model, commands: [...(shown.commands ?? []), Upload({ id })] }
              },
              Finished: ({ id }) => {
                const settled = App.children.toasts.helpers.settle(id, {
                  type: 'success',
                  title: 'Uploaded',
                  description: 'report.pdf is in your files.',
                })(model)
                return { model: settled.model, commands: [...(settled.commands ?? [])] }
              },
            }),
          ),
        }),
        view: ({ style, model, onMessage, h }) =>
          h.div(
            [],
            [
              Button.view(
                { label: 'Upload report.pdf', onClick: onMessage(App.Message.Started()), style: Primary },
                h,
              ),
              Toast.view(
                {
                  model: model.toasts,
                  onMessage: message => onMessage(App.Message.GotToastsMessage({ message })),
                  label: 'Uploads',
                  icons: { loading: Spinner.view({ label: 'Uploading', style: Ring }, h) },
                  style,
                },
                h,
              ),
            ],
          ),
      })

      In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

      Actions and a cancel #

        import { Bundle } from 'foldkit-bundle'
        import { Bundles, Button, Recipes, Toast, ToastSlots } from 'foldkit-mixins-ui'
        import { example } from '../../gallery/example.js'
        
        const Primary = Recipes.Button.style({})
        
        // Actions and a cancel: each action dismisses the toast and says its `value`
        // in `Acted`, which `onOut` answers (here dropped: an application undoes the
        // archive there); the cancel only dismisses. `keepFocus` hands focus to a
        // neighbouring toast's button when the toast that holds it leaves, instead of
        // dropping it on the page.
        const App = Bundle.compose({}).pipe(
          Bundle.withMessages({ Archived: {} }),
          Bundle.withChild('toasts', Bundles.Toast, { args: { id: 'archive' }, onOut: Bundle.ignore }),
        )
        
        export default example({
          title: 'Actions and a cancel',
          slots: ToastSlots,
          recipe: Recipes.Toast,
          state: App.placements.runtime({
            Model: App.Model,
            initial: {},
            update: App.placements.update(model =>
              App.children.toasts.helpers.show({
                title: 'Thread archived',
                description: 'It left your inbox.',
                actions: [
                  { label: 'Undo', value: 'undo' },
                  { label: 'Open', value: 'open' },
                ],
                cancel: 'Later',
              })(model),
            ),
          }),
          view: ({ style, model, onMessage, h }) =>
            h.div(
              [],
              [
                Button.view(
                  {
                    label: 'Archive the thread',
                    onClick: onMessage(App.Message.Archived()),
                    style: Primary,
                  },
                  h,
                ),
                Toast.view(
                  {
                    model: model.toasts,
                    onMessage: message => onMessage(App.Message.GotToastsMessage({ message })),
                    label: 'Archive',
                    mixins: Toast.keepFocus,
                    style,
                  },
                  h,
                ),
              ],
            ),
        })

        In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

        Rich colors #

          import { Schema } from 'effect'
          import { Bundle } from 'foldkit-bundle'
          import { Bundles, Button, Recipes, Toast, ToastSlots } from 'foldkit-mixins-ui'
          import { example } from '../../gallery/example.js'
          
          const Choose = Recipes.Button.style({ tone: 'neutral', variant: 'outline' })
          
          const types = ['info', 'success', 'warning', 'error'] as const
          
          // Each type on its own tint and edge: the recipe's `tone: 'rich'`, over the
          // same markup, so nothing in the view changes.
          const App = Bundle.compose({}).pipe(
            Bundle.withMessages({ Raised: { type: Schema.Literals(types) } }),
            Bundle.withChild('toasts', Bundles.Toast, { args: { id: 'toasts-rich' }, onOut: Bundle.ignore }),
          )
          
          export default example({
            title: 'Rich colors',
            slots: ToastSlots,
            recipe: Recipes.Toast,
            pins: { tone: 'rich' },
            state: App.placements.runtime({
              Model: App.Model,
              initial: {},
              update: App.placements.update((model, { type }) =>
                App.children.toasts.helpers.show({ type, title: `A ${type} toast` })(model),
              ),
            }),
            view: ({ style, model, onMessage, h }) =>
              h.div(
                [h.Style({ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' })],
                [
                  ...types.map(type =>
                    Button.view(
                      { label: type, onClick: onMessage(App.Message.Raised({ type })), style: Choose },
                      h,
                    ),
                  ),
                  Toast.view(
                    {
                      model: model.toasts,
                      onMessage: message => onMessage(App.Message.GotToastsMessage({ message })),
                      label: 'Notifications, rich',
                      style,
                    },
                    h,
                  ),
                ],
              ),
          })

          In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

          Inverted #

            import { Bundle } from 'foldkit-bundle'
            import { Bundles, Button, Recipes, Toast, ToastSlots } from 'foldkit-mixins-ui'
            import { example } from '../../gallery/example.js'
            
            const Primary = Recipes.Button.style({})
            
            // The text's ink as the card, as Sonner's inverted toasts: dark on a light
            // page, light on a dark one. The recipe's `tone: 'invert'`; its buttons keep
            // their hover.
            const App = Bundle.compose({}).pipe(
              Bundle.withMessages({ Raised: {} }),
              Bundle.withChild('toasts', Bundles.Toast, { args: { id: 'inverted' }, onOut: Bundle.ignore }),
            )
            
            export default example({
              title: 'Inverted',
              slots: ToastSlots,
              recipe: Recipes.Toast,
              pins: { tone: 'invert' },
              state: App.placements.runtime({
                Model: App.Model,
                initial: {},
                update: App.placements.update(model =>
                  App.children.toasts.helpers.show({
                    type: 'success',
                    title: 'Payment received',
                    description: 'A receipt is on its way.',
                    actions: [{ label: 'View receipt', value: 'receipt' }],
                    cancel: 'Dismiss',
                  })(model),
                ),
              }),
              view: ({ style, model, onMessage, h }) =>
                h.div(
                  [],
                  [
                    Button.view(
                      { label: 'Take payment', onClick: onMessage(App.Message.Raised()), style: Primary },
                      h,
                    ),
                    Toast.view(
                      {
                        model: model.toasts,
                        onMessage: message => onMessage(App.Message.GotToastsMessage({ message })),
                        label: 'Payments',
                        style,
                      },
                      h,
                    ),
                  ],
                ),
            })

            In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

            Positions #

                        import { Bundle } from 'foldkit-bundle'
                        import { Bundles, Button, Recipes, Toast, ToastSlots } from 'foldkit-mixins-ui'
                        import { example } from '../../gallery/example.js'
                        
                        const Choose = Recipes.Button.style({ tone: 'neutral', variant: 'outline' })
                        
                        // A stack stands where its Model says (`position`), so a place is a stack:
                        // one Bundle each, in a field of its own.
                        const App = Bundle.compose({}).pipe(
                          Bundle.withMessages({ Raised: { place: Toast.Position } }),
                          Bundle.withChild('topStart', Bundles.Toast, {
                            args: { id: 'positions-top-start', position: 'top-start' },
                            onOut: Bundle.ignore,
                          }),
                          Bundle.withChild('topCenter', Bundles.Toast, {
                            args: { id: 'positions-top-center', position: 'top-center' },
                            onOut: Bundle.ignore,
                          }),
                          Bundle.withChild('topEnd', Bundles.Toast, {
                            args: { id: 'positions-top-end', position: 'top-end' },
                            onOut: Bundle.ignore,
                          }),
                          Bundle.withChild('bottomStart', Bundles.Toast, {
                            args: { id: 'positions-bottom-start', position: 'bottom-start' },
                            onOut: Bundle.ignore,
                          }),
                          Bundle.withChild('bottomCenter', Bundles.Toast, {
                            args: { id: 'positions-bottom-center', position: 'bottom-center' },
                            onOut: Bundle.ignore,
                          }),
                          Bundle.withChild('bottomEnd', Bundles.Toast, {
                            args: { id: 'positions-bottom-end', position: 'bottom-end' },
                            onOut: Bundle.ignore,
                          }),
                        )
                        
                        const show = {
                          'top-start': App.children.topStart.helpers.show,
                          'top-center': App.children.topCenter.helpers.show,
                          'top-end': App.children.topEnd.helpers.show,
                          'bottom-start': App.children.bottomStart.helpers.show,
                          'bottom-center': App.children.bottomCenter.helpers.show,
                          'bottom-end': App.children.bottomEnd.helpers.show,
                        }
                        
                        export default example({
                          title: 'Positions',
                          slots: ToastSlots,
                          recipe: Recipes.Toast,
                          state: App.placements.runtime({
                            Model: App.Model,
                            initial: {},
                            update: App.placements.update((model, { place }) =>
                              show[place]({ type: 'success', title: `Saved, at ${place}` })(model),
                            ),
                          }),
                          view: ({ style, model, onMessage, h }) =>
                            h.div(
                              [h.Style({ display: 'flex', flexWrap: 'wrap', gap: '0.5rem' })],
                              [
                                ...Toast.Position.literals.map(place =>
                                  Button.view(
                                    { label: place, onClick: onMessage(App.Message.Raised({ place })), style: Choose },
                                    h,
                                  ),
                                ),
                                Toast.view(
                                  {
                                    model: model.topStart,
                                    onMessage: message => onMessage(App.Message.GotTopStartMessage({ message })),
                                    label: 'Notifications, top start',
                                    style,
                                  },
                                  h,
                                ),
                                Toast.view(
                                  {
                                    model: model.topCenter,
                                    onMessage: message => onMessage(App.Message.GotTopCenterMessage({ message })),
                                    label: 'Notifications, top center',
                                    style,
                                  },
                                  h,
                                ),
                                Toast.view(
                                  {
                                    model: model.topEnd,
                                    onMessage: message => onMessage(App.Message.GotTopEndMessage({ message })),
                                    label: 'Notifications, top end',
                                    style,
                                  },
                                  h,
                                ),
                                Toast.view(
                                  {
                                    model: model.bottomStart,
                                    onMessage: message => onMessage(App.Message.GotBottomStartMessage({ message })),
                                    label: 'Notifications, bottom start',
                                    style,
                                  },
                                  h,
                                ),
                                Toast.view(
                                  {
                                    model: model.bottomCenter,
                                    onMessage: message => onMessage(App.Message.GotBottomCenterMessage({ message })),
                                    label: 'Notifications, bottom center',
                                    style,
                                  },
                                  h,
                                ),
                                Toast.view(
                                  {
                                    model: model.bottomEnd,
                                    onMessage: message => onMessage(App.Message.GotBottomEndMessage({ message })),
                                    label: 'Notifications, bottom end',
                                    style,
                                  },
                                  h,
                                ),
                              ],
                            ),
                        })

                        In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

                        Your own payload #

                        import { Schema } from 'effect'
                        import * as Command from 'foldkit/command'
                        import { defineMessageUnion } from 'foldkit/message'
                        import { SlotView } from 'foldkit-mixins'
                        import {
                          Button,
                          ButtonSlots,
                          Item,
                          ItemSlots,
                          Recipes,
                          Toast,
                          ToastSlots,
                          ToastView,
                        } from 'foldkit-mixins-ui'
                        import { example } from '../../gallery/example.js'
                        import { forSlots } from '../../snippets/theme.js'
                        
                        const Primary = Recipes.Button.style({})
                        const Dismiss = Recipes.Button.style({ tone: 'neutral', variant: 'ghost', size: 'sm' })
                        // The toast's card pads the notice, so the row adds none of its own.
                        const Notice = forSlots(ItemSlots)(
                          Recipes.Item.extend({ variants: { density: { comfortable: { root: { padding: '0' } } } } })({}),
                        )
                        
                        // Your own payload: `ToastView.make(schema)` binds upstream's toast to what an
                        // entry holds, and the application draws each entry, with the stack's
                        // countdown, hold and swipe still the component's. The payload toast's state
                        // is the application's: it declares the field and folds the stack itself.
                        const Payload = Schema.Struct({ title: Schema.String, text: Schema.String })
                        // Annotated: the inferred type names a foldkit internal module.
                        const Notices: ReturnType<typeof ToastView.make<typeof Payload.Type, typeof Payload.Encoded>> =
                          ToastView.make(Payload)
                        
                        const Message = defineMessageUnion({
                          Saved: {},
                          GotNotices: { message: Notices.Message },
                        })
                        
                        const got = (commands: ReadonlyArray<Command.Command<typeof Notices.Message.Type>> = []) =>
                          Command.mapMessages(commands, message => Message.GotNotices({ message }))
                        
                        export default example({
                          title: 'Your own payload',
                          slots: ToastSlots,
                          recipe: Recipes.Toast,
                          state: {
                            Model: Schema.Struct({ notices: Notices.Model }),
                            Message,
                            init: () => ({ model: { notices: Notices.init({ id: 'notices' }) } }),
                            update: (model, message) =>
                              Message.match(message, {
                                Saved: () => {
                                  const shown = Notices.show(model.notices, {
                                    payload: { title: 'Draft saved', text: 'Autosaved a moment ago.' },
                                    variant: 'Success',
                                  })
                                  return { model: { notices: shown.model }, commands: got(shown.commands) }
                                },
                                GotNotices: ({ message }) => {
                                  const next = Notices.update(model.notices, message)
                                  return { model: { notices: next.model }, commands: got(next.commands) }
                                },
                              }),
                          },
                          view: ({ style, model, onMessage, h }) =>
                            h.div(
                              [],
                              [
                                Button.view(
                                  { label: 'Save draft', onClick: onMessage(Message.Saved()), style: Primary },
                                  h,
                                ),
                                h.submodel({
                                  slotId: model.notices.id,
                                  model: model.notices,
                                  view: Notices.view,
                                  viewInputs: {
                                    position: 'BottomRight',
                                    entryToView: (entry, handlers) =>
                                      Item.view(
                                        {
                                          title: entry.payload.title,
                                          description: entry.payload.text,
                                          actions: h.button(
                                            SlotView.buildersFor(ButtonSlots, [Dismiss.mixin], {
                                              input: undefined,
                                              h,
                                            }).button.attrs([
                                              ...handlers.dismiss,
                                              h.Type('button'),
                                              h.AriaLabel('Dismiss'),
                                            ]),
                                            ['✕'],
                                          ),
                                          style: Notice,
                                        },
                                        h,
                                      ),
                                    toView: Toast.toView([style.mixin], { h }, ({ container, entries }) =>
                                      h.div(
                                        container,
                                        entries.map(entry => h.keyed('div')(entry.id, entry.attributes, [entry.content])),
                                      ),
                                    ),
                                  },
                                  toParentMessage: message => onMessage(Message.GotNotices({ message })),
                                }),
                              ],
                            ),
                        })

                        In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

                        Progress #

                        import { Duration, Effect, Option, Schema } from 'effect'
                        import * as Command from 'foldkit/command'
                        import { defineMessageUnion } from 'foldkit/message'
                        import { Button, Progress, Recipes, Toast, ToastSlots, ToastView } from 'foldkit-mixins-ui'
                        import { example } from '../../gallery/example.js'
                        
                        const Primary = Recipes.Button.style({})
                        const Bar = Recipes.Progress.style({})
                        
                        // A toast that shows progress: the entry holds a percentage, and `revise`
                        // replaces it as the work reports, keeping the toast's place and its
                        // animation. The toast is sticky while it runs and dismissed at the end.
                        const Upload = Schema.Struct({ name: Schema.String, percent: Schema.Number })
                        // Annotated: the inferred type names a foldkit internal module.
                        const Uploads: ReturnType<typeof ToastView.make<typeof Upload.Type, typeof Upload.Encoded>> =
                          ToastView.make(Upload)
                        
                        const Message = defineMessageUnion({
                          Started: {},
                          Advanced: { id: Schema.String, percent: Schema.Number },
                          GotUploads: { message: Uploads.Message },
                        })
                        
                        const Advance = Command.define('Advance', {
                          args: { id: Schema.String, percent: Schema.Number },
                          messages: [Message.Advanced],
                          execute: ({ id, percent }) =>
                            Effect.sleep(Duration.millis(500)).pipe(Effect.as(Message.Advanced({ id, percent }))),
                        })
                        
                        const got = (commands: ReadonlyArray<Command.Command<typeof Uploads.Message.Type>> = []) =>
                          Command.mapMessages(commands, message => Message.GotUploads({ message }))
                        
                        export default example({
                          title: 'Progress',
                          slots: ToastSlots,
                          recipe: Recipes.Toast,
                          state: {
                            Model: Schema.Struct({ uploads: Uploads.Model }),
                            Message,
                            init: () => ({ model: { uploads: Uploads.init({ id: 'toasts-progress' }) } }),
                            update: (model, message) =>
                              Message.match(message, {
                                Started: () => {
                                  const shown = Uploads.show(model.uploads, {
                                    payload: { name: 'holiday.mov', percent: 0 },
                                    sticky: true,
                                  })
                                  const entry = shown.model.entries[0]
                                  return {
                                    model: { uploads: shown.model },
                                    commands: [
                                      ...got(shown.commands),
                                      ...(entry === undefined ? [] : [Advance({ id: entry.id, percent: 25 })]),
                                    ],
                                  }
                                },
                                Advanced: ({ id, percent }) => {
                                  const revised = Uploads.revise(model.uploads, id, { name: 'holiday.mov', percent })
                                  if (percent < 100) {
                                    return {
                                      model: { uploads: revised },
                                      commands: [Advance({ id, percent: percent + 25 })],
                                    }
                                  }
                                  const done = Uploads.dismiss(revised, id)
                                  return { model: { uploads: done.model }, commands: got(done.commands) }
                                },
                                GotUploads: ({ message }) => {
                                  const next = Uploads.update(model.uploads, message)
                                  return { model: { uploads: next.model }, commands: got(next.commands) }
                                },
                              }),
                          },
                          view: ({ style, model, onMessage, h }) =>
                            h.div(
                              [],
                              [
                                Button.view(
                                  { label: 'Upload holiday.mov', onClick: onMessage(Message.Started()), style: Primary },
                                  h,
                                ),
                                h.submodel({
                                  slotId: model.uploads.id,
                                  model: model.uploads,
                                  view: Uploads.view,
                                  viewInputs: {
                                    position: 'BottomRight',
                                    entryToView: entry =>
                                      h.div(
                                        [h.Style({ display: 'grid', gap: '0.5rem', minInlineSize: '14rem' })],
                                        [
                                          h.strong([], [`Uploading ${entry.payload.name}`]),
                                          Progress.view(
                                            {
                                              id: `${entry.id}-bar`,
                                              label: entry.payload.name,
                                              value: Option.some(entry.payload.percent),
                                              showValue: true,
                                              style: Bar,
                                            },
                                            h,
                                          ),
                                        ],
                                      ),
                                    toView: Toast.toView([style.mixin], { h }, ({ container, entries }) =>
                                      h.div(
                                        container,
                                        entries.map(entry => h.keyed('div')(entry.id, entry.attributes, [entry.content])),
                                      ),
                                    ),
                                  },
                                  toParentMessage: message => onMessage(Message.GotUploads({ message })),
                                }),
                              ],
                            ),
                        })

                        In your application: recipe goes to forSlots, state to Bundle.withChild, and the body of view is the call. example is this site’s harness.

                        Usage

                        Each example above is a module of its own, shown whole and run as shown, over the theme module Create a theme writes. The page hands it the style picked above.

                        The recipe ↗This code ↗

                        • Keeping focus when something is removed A control that leaves the page takes its focus with it: say where focus goes next, to a neighbour (FocusRecovery), to the opener (focusReturn) or to a control (keepFocus).