# Note: Chromatic is a separate workflow for coder.yaml as suggested by the
# chromatic docs. Explicitly, Chromatic works best on 'push' instead of other
# event types (like pull request), keep in mind that it works build-over-build
# by storing snapshots.
#
# SEE: https://www.chromatic.com/docs/ci
name: chromatic

# REMARK: We want Chromatic to run whenever anything in the FE or its deps
#         change, including node_modules and generated code. Currently, all
#         node_modules and generated code live in site. If any of these are
#         hoisted, we'll want to adjust the paths filter to account for them.
on:
  push:
    paths:
      - site/**
    branches:
      - main
    tags:
      - "*"

  pull_request:
    paths:
      - site/**

jobs:
  deploy:
    # REMARK: this is only used to build storybook and deploy it to Chromatic.
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
        with:
          # Required by Chromatic for build-over-build history, otherwise we
          # only get 1 commit on shallow checkout.
          fetch-depth: 0

      - name: Install dependencies
        run: cd site && yarn

      # This step is not meant for mainline because any detected changes to
      # storybook snapshots will require manual approval/review in order for
      # the check to pass. This is desired in PRs, but not in mainline.
      - name: Publish to Chromatic (non-mainline)
        if: github.ref != 'refs/heads/main' && github.repository_owner == 'coder'
        uses: chromaui/action@v1
        with:
          buildScriptName: "storybook:build"
          exitOnceUploaded: true
          # Chromatic states its fine to make this token public. See:
          # https://www.chromatic.com/docs/github-actions#forked-repositories
          projectToken: 695c25b6cb65
          workingDir: "./site"

      # This is a separate step for mainline only that auto accepts and changes
      # instead of holding CI up. Since we squash/merge, this is defensive to
      # avoid the same changeset from requiring review once squashed into
      # main. Chromatic is supposed to be able to detect that we use squash
      # commits, but it's good to be defensive in case, otherwise CI remains
      # infinitely "in progress" in mainline unless we re-review each build.
      - name: Publish to Chromatic (mainline)
        if: github.ref == 'refs/heads/main' && github.repository_owner == 'coder'
        uses: chromaui/action@v1
        with:
          autoAcceptChanges: true
          buildScriptName: "storybook:build"
          projectToken: 695c25b6cb65
          workingDir: "./site"
