index.ts 5.4 KB
Newer Older
L
LeoKu 已提交
1 2 3 4 5 6 7 8
import {
  type EarringsShape,
  type GlassesShape,
  BeardShape,
  Gender,
  TopsShape,
} from '@/enums'
import { type AvatarOption, type None } from '@/types'
L
LeoKu 已提交
9

L
LeoKu 已提交
10
import { AVATAR_LAYER, NONE, SETTINGS, SPECIAL_AVATARS } from './constant'
L
LeoKu 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

/**
 * get a random value from an array
 */
function getRandomValue<Item = unknown>(
  arr: Item[],
  {
    avoid = [],
    usually = [],
  }: { avoid?: unknown[]; usually?: (Item | 'none')[] } = {}
): Item {
  const avoidValues = avoid.filter(Boolean)
  const filteredArr = arr.filter((it) => !avoidValues.includes(it))

  const usuallyValues = usually
    .filter(Boolean)
    .reduce<Item[]>((acc, cur) => acc.concat(new Array(15).fill(cur)), [])

  const finalArr = filteredArr.concat(usuallyValues)

  const randomIdx = Math.floor(Math.random() * finalArr.length)
  const randomValue = finalArr[randomIdx]

  return randomValue
}

L
LeoKu 已提交
37 38 39 40 41 42
export function getRandomFillColor() {
  return SETTINGS.commonColors[
    Math.floor(Math.random() * SETTINGS.commonColors.length)
  ]
}

L
LeoKu 已提交
43 44 45 46
export function getRandomAvatarOption(
  presetOption: Partial<AvatarOption> = {},
  useOption: Partial<AvatarOption> = {}
): AvatarOption {
L
LeoKu 已提交
47 48 49 50 51 52 53 54 55 56
  const gender = getRandomValue(SETTINGS.gender)

  const beardList: BeardShape[] = []
  let topList: TopsShape[] = [TopsShape.Danny, TopsShape.Wave, TopsShape.Pixie]

  if (gender === Gender.Male) {
    beardList.push(BeardShape.Scruff)
    topList = SETTINGS.topsShape.filter((shape) => !topList.includes(shape))
  }

L
LeoKu 已提交
57 58 59 60
  const beardShape = getRandomValue<BeardShape | None>(beardList, {
    usually: [NONE],
  })

L
LeoKu 已提交
61 62 63 64 65
  const hairShape = getRandomValue(topList, {
    avoid: [useOption.widgets?.tops?.shape],
  })
  const hairColor = getRandomFillColor()

L
LeoKu 已提交
66
  const avatarOption: AvatarOption = {
L
LeoKu 已提交
67 68
    gender,

L
LeoKu 已提交
69 70 71 72 73
    wrapperShape:
      presetOption?.wrapperShape || getRandomValue(SETTINGS.wrapperShape),

    background: {
      color: getRandomValue(SETTINGS.backgroundColor, {
L
LeoKu 已提交
74 75 76 77
        avoid: [
          useOption.background?.color,
          hairShape === TopsShape.Punk && hairColor, // Handle special cases and prevent color conflicts.
        ],
L
LeoKu 已提交
78 79 80 81 82 83 84 85
      }),
    },

    widgets: {
      face: {
        shape: getRandomValue(SETTINGS.faceShape),
      },
      tops: {
L
LeoKu 已提交
86 87
        shape: hairShape,
        fillColor: hairColor,
L
LeoKu 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
      },
      ear: {
        shape: getRandomValue(SETTINGS.earShape, {
          avoid: [useOption.widgets?.ear?.shape],
        }),
      },
      earrings: {
        shape: getRandomValue<EarringsShape | None>(SETTINGS.earringsShape, {
          usually: [NONE],
        }),
      },
      eyebrows: {
        shape: getRandomValue(SETTINGS.eyebrowsShape, {
          avoid: [useOption.widgets?.eyebrows?.shape],
        }),
      },
      eyes: {
        shape: getRandomValue(SETTINGS.eyesShape, {
          avoid: [useOption.widgets?.eyes?.shape],
        }),
      },
      nose: {
        shape: getRandomValue(SETTINGS.noseShape, {
          avoid: [useOption.widgets?.nose?.shape],
        }),
      },
      glasses: {
        shape: getRandomValue<GlassesShape | None>(SETTINGS.glassesShape, {
          usually: [NONE],
        }),
      },
      mouth: {
        shape: getRandomValue(SETTINGS.mouthShape, {
          avoid: [useOption.widgets?.mouth?.shape],
        }),
      },
      beard: {
L
LeoKu 已提交
125 126 127 128 129 130
        shape: beardShape,

        // HACK:
        ...(beardShape === BeardShape.Scruff
          ? { zIndex: AVATAR_LAYER['mouth'].zIndex - 1 }
          : undefined),
L
LeoKu 已提交
131 132 133 134 135
      },
      clothes: {
        shape: getRandomValue(SETTINGS.clothesShape, {
          avoid: [useOption.widgets?.clothes?.shape],
        }),
L
LeoKu 已提交
136
        fillColor: getRandomFillColor(),
L
LeoKu 已提交
137 138 139 140 141 142 143
      },
    },
  }

  return avatarOption
}

L
LeoKu 已提交
144
export function getSpecialAvatarOption(): AvatarOption {
L
LeoKu 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
  return SPECIAL_AVATARS[Math.floor(Math.random() * SPECIAL_AVATARS.length)]
}

export function showConfetti() {
  import('canvas-confetti').then((confetti) => {
    const canvasEle: HTMLCanvasElement | null =
      document.querySelector('#confetti')

    if (!canvasEle) {
      return
    }

    const myConfetti = confetti.create(canvasEle, {
      resize: true,
      useWorker: true,
      disableForReducedMotion: true,
    })

    const duration = performance.now() + 1 * 1000

L
LeoKu 已提交
165
    const confettiColors = ['#6967fe', '#85e9f4', '#e16984']
L
LeoKu 已提交
166 167 168

    void (function frame() {
      myConfetti({
L
LeoKu 已提交
169
        particleCount: confettiColors.length,
L
LeoKu 已提交
170 171 172
        angle: 60,
        spread: 55,
        origin: { x: 0 },
L
LeoKu 已提交
173
        colors: confettiColors,
L
LeoKu 已提交
174 175
      })
      myConfetti({
L
LeoKu 已提交
176
        particleCount: confettiColors.length,
L
LeoKu 已提交
177 178 179
        angle: 120,
        spread: 55,
        origin: { x: 1 },
L
LeoKu 已提交
180
        colors: confettiColors,
L
LeoKu 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
      })

      if (performance.now() < duration) {
        requestAnimationFrame(frame)
      }
    })()
  })
}

export function highlightJSON(json: string): string {
  if (!json) {
    return ''
  }

  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2)
  }

  json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')

  return json.replace(
    /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
    (match) => {
      let cls = ''
      if (/^"/.test(match)) {
        if (/:$/.test(match)) {
          cls = 'key'
        } else {
          cls = 'string'
        }
      } else if (/true|false/.test(match)) {
        cls = 'boolean'
      } else if (/null/.test(match)) {
        cls = 'null'
      } else {
        cls = 'number'
      }
      return `<span class="token ${cls}">${match}</span>`
    }
  )
}