File size: 6,246 Bytes
5c239ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
/* HTML generation */

const TYPES = {
  Grass: '🍃',
  Fire: '🔥',
  Water: '💧',
  Lightning: '⚡',
  Fighting: '✊',
  Psychic: '👁️',
  Colorless: '⭐',
  Darkness: '🌑',
  Metal: '⚙️',
  Dragon: '🐲',
  Fairy: '🧚',
};

const energyHTML = (type, types = TYPES) => {
  return `<span title="${type} energy" class="energy ${type.toLowerCase()}">${types[type]}</span>`;
};

const attackDescriptionHTML = (text) => {
  if (!text) {
    return '';
  }

  let fontSize;

  if (text.length > 185) {
    fontSize = 0.7;
  } else if (text.length > 140) {
    fontSize = 0.8;
  } else if (text.length > 90) {
    fontSize = 0.9;
  }

  return `<span class="attack-details"${fontSize ? ` style="font-size: ${fontSize.toString()}em"` : ''}>${text}</span>`;
};

const attackRowsHTML = (attacks) => {
  return attacks
    .map((attack) => {
      const { cost, damage, name, text } = attack;

      return `
<li class="attacks-row grid-three">
  <div class="attack-cost">
    ${cost.map((energy) => energyHTML(energy)).join('')}
  </div>
  <span class="attack-text">
    <span class="attack-name">${name}</span>
    ${attackDescriptionHTML(text)}
  </span>
  <span class="attack-damage">${damage ? damage : ''}</span>
</li>
<hr role="presentation" />`;
    })
    .join('');
};

const cardHTML = (details) => {
  const { hp, energy_type, species, length, weight, attacks, weakness, resistance, retreat, description, rarity } =
    details;

  const poke_name = details.name; // `name` would be reserved JS word

  return `
<div class="pokecard ${energy_type.toLowerCase()}" data-displayed="true">
  <p class="evolves">Basic Pokémon</p>
  <header>
    <h1 class="name">${poke_name}</h1>
    <div>
      <span class="hp">${hp} HP</span>
      ${energyHTML(energy_type)}
    </div>
  </header>
  <img class="picture frame" alt="AI generated Pokémon called ${poke_name}" />
  <div class="species frame">
    ${species} Pokémon. Length: ${length.feet}'${length.inches}", Weight: ${weight}
  </div>
  <ul class="attacks">
    ${attackRowsHTML(attacks)}
  </ul>
  <div class="multipliers">
    <div class="weakness">
      <span>weakness</span>
      ${weakness ? energyHTML(weakness) : ''}
    </div>
    <div class="resistance">
      <span>resistance</span>
      ${resistance ? energyHTML(resistance) : ''}
      <span class="resistance-total"
        >${resistance ? '-30' : ''}</span
      >
    </div>
    <div class="retreat-cost">
      <span>retreat cost</span>
      <div>${energyHTML('Colorless').repeat(retreat)}</div>
    </div>
  </div>
  <p class="description frame">${description}</p>
  <div class="footer grid-three">
    <span
      ><a
        href="https://huggingface.co/minimaxir/ai-generated-pokemon-rudalle"
        >Illus. Max Woolf</a
      ></span
    >
    <span><a href="">2022 Hugging Face</a></span>
    <span>${rarity}</span>
  </div>
</div>`;
};

/* Utility */

const getBasePath = () => {
  return document.location.origin + document.location.pathname;
};

const generateDetails = async () => {
  const details = await fetch(`${getBasePath()}/details`);
  return await details.json();
};

const createTask = async (prompt) => {
  const taskResponse = await fetch(`${getBasePath()}task/create?prompt=${prompt}`);
  const task = await taskResponse.json();

  return task;
};

const queueTask = (task_id) => {
  fetch(`${getBasePath()}task/queue?task_id=${task_id}`);
};

const pollTask = async (task) => {
  const taskResponse = await fetch(`${getBasePath()}task/poll?task_id=${task.task_id}`);

  return await taskResponse.json();
};

const longPollTask = async (task, interval = 5_000, max) => {
  if (task.status === 'complete' || (max && task.poll_count > max)) {
    return task;
  }

  const taskResponse = await fetch(`${getBasePath()}task/poll?task_id=${task.task_id}`);

  task = await taskResponse.json();

  if (task.status === 'complete' || task.poll_count > max) {
    return task;
  }

  await new Promise((resolve) => setTimeout(resolve, interval));

  return await longPollTask(task, interval, max);
};

/* DOM */

const generateButton = document.querySelector('button.generate');

const rotateCard = () => {
  const RANGE = 0.1;
  const INTERVAL = 13; // ~75 per second
  let previousTime = 0;

  // Throttle closure
  return (card, containerMouseEvent) => {
    const currentTime = performance.now();

    if (currentTime - previousTime > INTERVAL) {
      previousTime = currentTime;

      const rect = card.getBoundingClientRect();

      const rotateX = (containerMouseEvent.clientY - rect.y - rect.height / 2) * RANGE;
      const rotateY = -(containerMouseEvent.clientX - rect.x - rect.width / 2) * RANGE;

      card.style.setProperty('--rotate-x', rotateX + 'deg');
      card.style.setProperty('--rotate-y', rotateY + 'deg');
    }
  };
};

const cardRotationInitiator = (renderSection) => {
  let currentCard;

  return () => {
    let handleMouseMove;

    if (currentCard) {
      handleMouseMove = rotateCard().bind(null, currentCard);
      renderSection.removeEventListener('mousemove', handleMouseMove, true);
    }

    const newCard = document.querySelector('.pokecard');

    currentCard = newCard;

    handleMouseMove = rotateCard().bind(null, newCard);
    renderSection.addEventListener('mousemove', handleMouseMove, true);
  };
};

generateButton.addEventListener('click', async () => {
  const details = await generateDetails();
  console.log({ details });

  const renderSection = document.querySelector('section.render');
  const durationSeconds = document.querySelector('.duration > .seconds');
  const initialiseCardRotation = cardRotationInitiator(renderSection);
  let duration = 0.0;

  try {
    const task = await createTask(details.energy_type);

    queueTask(task.task_id);

    const incrementSeconds = setInterval(() => {
      duration += 0.1;
      durationSeconds.textContent = duration.toFixed(1).toString();
    }, 100);

    const completedTask = await longPollTask(task);

    clearInterval(incrementSeconds);

    renderSection.innerHTML = cardHTML(details);

    const picture = document.querySelector('img.picture');
    picture.src = completedTask.value;

    initialiseCardRotation();
  } catch (err) {
    console.error(err);
  }
});