czapp-shared 1.0.38 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,118 @@
1
+ import { AvatarPresetId, ILevelDefinition, ILevelPalette, ILevelsConfig } from '../design/levels';
2
+ import { hslToHex, shiftHue } from './color';
3
+ import { DEFAULT_XP_AWARDS, LEVELS } from './level';
4
+
5
+ /**
6
+ * The built-in level definitions: what the apps show when no published configuration has been loaded (offline, first
7
+ * launch), and what the czapp-server xp_levels table is seeded with. They reproduce the original hard-coded levels:
8
+ * level 1 is the app's original orange design; each later level rotates it round the colour wheel to its own hue.
9
+ */
10
+
11
+ // the original design's colours (level 1)
12
+ const DESIGN = {
13
+ background: '#ece7e1',
14
+ card: '#f9f8f6',
15
+ brand: '#317a97',
16
+ brandMid: '#76b2cb',
17
+ brandLight: '#a7d2e4',
18
+ brandPale: '#cedfe8',
19
+ points: '#fcb64a',
20
+ streak: '#f0643f',
21
+ test: '#80bda6',
22
+ testDark: '#326451',
23
+ testText: '#4c836e',
24
+ leaderboardHighlight: '#fbe6c4',
25
+ divider: '#d9d3c9',
26
+ heatScale: ['#dddddd', '#f8d9ab', '#f49911', '#e37639', '#df6c4a', '#cf4132'],
27
+ };
28
+
29
+ // hue of the alpha logo's main orange (#f5831f) - level 1's hue
30
+ const BASE_HUE = 28;
31
+
32
+ // each level's hue: orange (the original design), then on round the colour wheel; level 10 is gold
33
+ const LEVEL_HUES = [BASE_HUE, 50, 125, 175, 210, 240, 275, 320, 355, 45];
34
+
35
+ const NAMES: { en: string, cz: string }[] = [
36
+ { en: 'Cool Catalyst', cz: 'Klidný katalyzátor' },
37
+ { en: 'Swift Starter', cz: 'Svižný startér' },
38
+ { en: 'Bold Builder', cz: 'Bystrý budovatel' },
39
+ { en: 'Word Wrangler', cz: 'Slovní sběratel' },
40
+ { en: 'Fluent Flame', cz: 'Plynulý plamen' },
41
+ { en: 'Mighty Master', cz: 'Mocný mistr' },
42
+ { en: 'Radiant Rockstar', cz: 'Zářivý znalec' },
43
+ { en: 'Wise Wizard', cz: 'Moudrý mág' },
44
+ { en: 'Legendary Linguist', cz: 'Legendární lingvista' },
45
+ { en: 'Absolute Alpha', cz: 'Absolutní alfa' },
46
+ ];
47
+
48
+ const PRESETS: AvatarPresetId[] = [
49
+ AvatarPresetId.COOL_CATALYST,
50
+ AvatarPresetId.SWIFT_STARTER,
51
+ AvatarPresetId.BOLD_BUILDER,
52
+ AvatarPresetId.WORD_WRANGLER,
53
+ AvatarPresetId.FLUENT_FLAME,
54
+ AvatarPresetId.MIGHTY_MASTER,
55
+ AvatarPresetId.RADIANT_ROCKSTAR,
56
+ AvatarPresetId.WISE_WIZARD,
57
+ AvatarPresetId.LEGENDARY_LINGUIST,
58
+ AvatarPresetId.ABSOLUTE_ALPHA,
59
+ ];
60
+
61
+ /**
62
+ * A full palette generated from one hue: the original design rotated round the colour wheel by (hue - level 1's
63
+ * hue), with the level's accent shades derived from the hue itself. The Level Designer's "generate from hue" uses
64
+ * this as a starting point.
65
+ */
66
+ export const generatePalette = (hue: number): ILevelPalette => {
67
+ const shift = hue - BASE_HUE;
68
+ const rotate = (hex: string) => shiftHue(hex, shift);
69
+ // yellow-ish hues read too light at the usual lightness, so darken them a little
70
+ const lightnessFix = hue >= 40 && hue <= 70 ? -0.08 : 0;
71
+ const accent = (s: number, l: number) => hslToHex({ h: hue, s, l: l + lightnessFix });
72
+ const isOriginal = shift === 0;
73
+ return {
74
+ background: rotate(DESIGN.background),
75
+ card: rotate(DESIGN.card),
76
+ brand: rotate(DESIGN.brand),
77
+ brandMid: rotate(DESIGN.brandMid),
78
+ brandLight: rotate(DESIGN.brandLight),
79
+ brandPale: rotate(DESIGN.brandPale),
80
+ points: rotate(DESIGN.points),
81
+ streak: rotate(DESIGN.streak),
82
+ test: rotate(DESIGN.test),
83
+ testDark: rotate(DESIGN.testDark),
84
+ testText: rotate(DESIGN.testText),
85
+ // level 1 keeps the original design's exact accent orange and progress track
86
+ accent: isOriginal ? '#e37639' : accent(0.75, 0.5),
87
+ accentDark: accent(0.7, 0.33),
88
+ accentLight: accent(0.9, 0.72),
89
+ accentPale: isOriginal ? '#f2e1d4' : accent(0.85, 0.93),
90
+ chartRetired: accent(0.7, 0.33),
91
+ chartLearning: isOriginal ? '#e37639' : accent(0.75, 0.5),
92
+ chartQueued: accent(0.9, 0.72),
93
+ leaderboardHighlight: rotate(DESIGN.leaderboardHighlight),
94
+ divider: rotate(DESIGN.divider),
95
+ heatScale: DESIGN.heatScale.map(rotate) as ILevelPalette['heatScale'],
96
+ celebrationGradient: [accent(0.9, 0.96), accent(0.85, 0.84), accent(0.8, 0.68)],
97
+ iconHueShift: shift,
98
+ };
99
+ };
100
+
101
+ export const DEFAULT_LEVEL_DEFINITIONS: ILevelDefinition[] = LEVELS.map((rules, i) => ({
102
+ level: rules.level,
103
+ xpThreshold: rules.xpThreshold,
104
+ minBestStreak: rules.minBestStreak,
105
+ names: NAMES[i],
106
+ palette: generatePalette(LEVEL_HUES[i]),
107
+ avatar: {
108
+ alphaHueShift: LEVEL_HUES[i] - BASE_HUE,
109
+ preset: { id: PRESETS[i], params: { speed: 1 } },
110
+ },
111
+ }));
112
+
113
+ // version 0 means "the built-in defaults" - any published configuration has a higher version
114
+ export const DEFAULT_LEVELS_CONFIG: ILevelsConfig = {
115
+ version: 0,
116
+ levels: DEFAULT_LEVEL_DEFINITIONS,
117
+ awards: DEFAULT_XP_AWARDS,
118
+ };
@@ -0,0 +1,101 @@
1
+ import { AvatarPresetId, ILevelDefinition, ILevelPalette, ILevelsConfig, IXpAwards } from '../design/levels';
2
+ import { isHexColor } from './color';
3
+
4
+ // limits on designer uploads, so one level row stays a sensible size
5
+ export const MAX_LOTTIE_BYTES = 512 * 1024;
6
+ export const MAX_SVG_BYTES = 128 * 1024;
7
+ export const MAX_LEVEL_NAME_LENGTH = 40;
8
+
9
+ const PALETTE_COLOUR_KEYS: (keyof ILevelPalette)[] = [
10
+ 'background', 'card', 'brand', 'brandMid', 'brandLight', 'brandPale', 'points', 'streak', 'test', 'testDark',
11
+ 'testText', 'accent', 'accentDark', 'accentLight', 'accentPale', 'chartRetired', 'chartLearning', 'chartQueued',
12
+ 'leaderboardHighlight', 'divider',
13
+ ];
14
+
15
+ const isNonNegativeInt = (value: unknown): value is number => Number.isInteger(value) && (value as number) >= 0;
16
+
17
+ /** Problems with one level definition (empty when it's valid). */
18
+ export const validateLevelDefinition = (level: ILevelDefinition): string[] => {
19
+ const errors: string[] = [];
20
+ const where = `level ${level?.level}`;
21
+ if (!Number.isInteger(level?.level) || level.level < 1) errors.push(`${where}: level must be a whole number from 1`);
22
+ if (!isNonNegativeInt(level?.xpThreshold)) errors.push(`${where}: XP threshold must be a whole number from 0`);
23
+ if (!isNonNegativeInt(level?.minBestStreak)) errors.push(`${where}: best streak must be a whole number from 0`);
24
+ for (const lang of ['en', 'cz'] as const) {
25
+ const name = level?.names?.[lang];
26
+ if (typeof name !== 'string' || !name.trim() || name.length > MAX_LEVEL_NAME_LENGTH) {
27
+ errors.push(`${where}: ${lang} name must be 1-${MAX_LEVEL_NAME_LENGTH} characters`);
28
+ }
29
+ }
30
+ const palette = level?.palette;
31
+ if (!palette) {
32
+ errors.push(`${where}: palette missing`);
33
+ } else {
34
+ for (const key of PALETTE_COLOUR_KEYS) {
35
+ if (!isHexColor(palette[key])) errors.push(`${where}: palette ${key} must be a hex colour`);
36
+ }
37
+ if (!Array.isArray(palette.heatScale) || palette.heatScale.length !== 6 || !palette.heatScale.every(isHexColor)) {
38
+ errors.push(`${where}: palette heatScale must be 6 hex colours`);
39
+ }
40
+ if (!Array.isArray(palette.celebrationGradient) || palette.celebrationGradient.length !== 3
41
+ || !palette.celebrationGradient.every(isHexColor)) {
42
+ errors.push(`${where}: palette celebrationGradient must be 3 hex colours`);
43
+ }
44
+ if (typeof palette.iconHueShift !== 'number' || !isFinite(palette.iconHueShift)) {
45
+ errors.push(`${where}: palette iconHueShift must be a number`);
46
+ }
47
+ }
48
+ const avatar = level?.avatar;
49
+ if (!avatar || typeof avatar.alphaHueShift !== 'number' || !isFinite(avatar.alphaHueShift)) {
50
+ errors.push(`${where}: avatar alphaHueShift must be a number`);
51
+ } else {
52
+ if (avatar.preset && !Object.values(AvatarPresetId).includes(avatar.preset.id)) {
53
+ errors.push(`${where}: unknown avatar preset '${avatar.preset.id}'`);
54
+ }
55
+ if (avatar.lottie !== undefined) {
56
+ if (typeof avatar.lottie !== 'string' || avatar.lottie.length > MAX_LOTTIE_BYTES) {
57
+ errors.push(`${where}: Lottie animation must be at most ${MAX_LOTTIE_BYTES / 1024}KB`);
58
+ } else {
59
+ try {
60
+ JSON.parse(avatar.lottie);
61
+ } catch {
62
+ errors.push(`${where}: Lottie animation is not valid JSON`);
63
+ }
64
+ }
65
+ }
66
+ for (const image of avatar.images ?? []) {
67
+ if (typeof image?.svg !== 'string' || !image.svg.includes('<svg') || image.svg.length > MAX_SVG_BYTES) {
68
+ errors.push(`${where}: image '${image?.id}' must be SVG markup of at most ${MAX_SVG_BYTES / 1024}KB`);
69
+ }
70
+ }
71
+ // no preset, Lottie or images is fine too: the avatar is then just the (hue-shifted) alpha logo
72
+ }
73
+ return errors;
74
+ };
75
+
76
+ export const validateXpAwards = (awards: IXpAwards): string[] =>
77
+ (['flashcardReview', 'test', 'perTestKnownAnswer', 'perWordRetired', 'dailyStreakBonusCap'] as (keyof IXpAwards)[])
78
+ .filter((key) => !isNonNegativeInt(awards?.[key]))
79
+ .map((key) => `XP award ${key} must be a whole number from 0`);
80
+
81
+ /**
82
+ * Problems with a whole configuration (empty when it can be published): every level valid, levels numbered 1..n
83
+ * with no gaps, XP thresholds rising from 0 and streak gates never falling.
84
+ */
85
+ export const validateLevelsConfig = (config: Pick<ILevelsConfig, 'levels' | 'awards'>): string[] => {
86
+ const errors = validateXpAwards(config.awards);
87
+ const levels = [...(config.levels ?? [])].sort((a, b) => a.level - b.level);
88
+ if (levels.length === 0) return [...errors, 'there must be at least one level'];
89
+ levels.forEach((level, i) => {
90
+ errors.push(...validateLevelDefinition(level));
91
+ if (level.level !== i + 1) errors.push(`levels must be numbered 1 to ${levels.length} with no gaps`);
92
+ if (i === 0 && level.xpThreshold !== 0) errors.push('level 1 must need 0 XP');
93
+ if (i > 0 && level.xpThreshold <= levels[i - 1].xpThreshold) {
94
+ errors.push(`level ${level.level} must need more XP than level ${levels[i - 1].level}`);
95
+ }
96
+ if (i > 0 && level.minBestStreak < levels[i - 1].minBestStreak) {
97
+ errors.push(`level ${level.level} can't need a shorter best streak than level ${levels[i - 1].level}`);
98
+ }
99
+ });
100
+ return [...new Set(errors)];
101
+ };
package/src/design/api.ts CHANGED
@@ -36,6 +36,8 @@ export enum ApiPath {
36
36
  HEALTH = '/health',
37
37
  LAST_WORDS_ADDED = '/lastWordsAdded',
38
38
  LEADERBOARD = '/leaderboard',
39
+ // published experience level definitions (ILevelsConfig), see design/levels.ts
40
+ LEVELS = '/levels',
39
41
  LEXEMES = '/lexemes',
40
42
  LEXEMES_ALL = '/lexemes/all',
41
43
  LEXEMES_COUNT = '/lexemes/count/:language',
@@ -218,7 +220,10 @@ export interface TestInitResponseData {
218
220
  export interface TestCompleteResponseData {
219
221
  user: IUserData;
220
222
  testResultIds: number[];
223
+ // Reward points earned by this completion - shown to the user on the results page.
221
224
  rewardPointsDelta: number;
225
+ // XP earned by this completion - internal, never shown; only used to detect a level-up. See concrete/level.ts.
226
+ xpDelta: number;
222
227
  vocabCheckActivity: IVocabCheckActivity[];
223
228
  }
224
229
  export interface HeatMapResponseData {
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Experience level definitions, as stored per level in the czapp-server xp_levels table (draft and published JSON),
3
+ * edited in the backoffice Level Designer and loaded by the apps from GET /levels. See concrete/level.ts for how a
4
+ * user's level is worked out, and concrete/levelDefaults.ts for the built-in defaults.
5
+ */
6
+
7
+ // The built-in, code-drawn avatar decorations (czapp-native-client LevelAvatar)
8
+ export enum AvatarPresetId {
9
+ COOL_CATALYST = 'coolCatalyst',
10
+ SWIFT_STARTER = 'swiftStarter',
11
+ BOLD_BUILDER = 'boldBuilder',
12
+ WORD_WRANGLER = 'wordWrangler',
13
+ FLUENT_FLAME = 'fluentFlame',
14
+ MIGHTY_MASTER = 'mightyMaster',
15
+ RADIANT_ROCKSTAR = 'radiantRockstar',
16
+ WISE_WIZARD = 'wiseWizard',
17
+ LEGENDARY_LINGUIST = 'legendaryLinguist',
18
+ ABSOLUTE_ALPHA = 'absoluteAlpha',
19
+ }
20
+
21
+ /**
22
+ * Named colour tokens for one level's theme. Every themed colour in the apps comes from one of these, so a designer
23
+ * can coordinate foreground, background and accents freely. All are #rrggbb hex.
24
+ */
25
+ export interface ILevelPalette {
26
+ // page backgrounds (home, streak, leaderboard) and cards
27
+ background: string;
28
+ card: string;
29
+ // the app's main blue in the original design: labels, icons, dictionary card, streak page text
30
+ brand: string;
31
+ brandMid: string;
32
+ brandLight: string;
33
+ brandPale: string;
34
+ // reward points and streak figures
35
+ points: string;
36
+ streak: string;
37
+ // unlocked-test card and tested-day markers
38
+ test: string;
39
+ testDark: string;
40
+ testText: string;
41
+ // the level's own colour: level name, progress bar, avatar decorations, celebration buttons
42
+ accent: string;
43
+ accentDark: string;
44
+ accentLight: string;
45
+ accentPale: string;
46
+ // progress chart series
47
+ chartRetired: string;
48
+ chartLearning: string;
49
+ chartQueued: string;
50
+ // leaderboard
51
+ leaderboardHighlight: string;
52
+ divider: string;
53
+ // streak heat map, from no activity to most
54
+ heatScale: [string, string, string, string, string, string];
55
+ // level-up celebration background, top to bottom
56
+ celebrationGradient: [string, string, string];
57
+ // degrees to rotate the multicoloured SVG artwork (footer menu, icons, logo) round the colour wheel
58
+ iconHueShift: number;
59
+ }
60
+
61
+ export interface ILevelAvatar {
62
+ // degrees to rotate the alpha logo's colours round the colour wheel
63
+ alphaHueShift: number;
64
+ // a built-in decoration, with its tunable settings (e.g. speed, scale)
65
+ preset?: { id: AvatarPresetId, params: Record<string, number | string> };
66
+ // a designer-made Lottie animation (Lottie JSON), drawn over the alpha and any preset
67
+ lottie?: string;
68
+ // extra SVG artwork (SVG markup), drawn over everything else, filling the avatar's square
69
+ images?: { id: string, svg: string }[];
70
+ }
71
+
72
+ export interface ILevelDefinition {
73
+ // 1-based, in order
74
+ level: number;
75
+ xpThreshold: number;
76
+ // best streak (days) also needed to reach this level
77
+ minBestStreak: number;
78
+ names: { en: string, cz: string };
79
+ palette: ILevelPalette;
80
+ avatar: ILevelAvatar;
81
+ }
82
+
83
+ // XP awarded per activity - see concrete/level.ts for how they combine
84
+ export interface IXpAwards {
85
+ flashcardReview: number;
86
+ test: number;
87
+ perTestKnownAnswer: number;
88
+ perWordRetired: number;
89
+ dailyStreakBonusCap: number;
90
+ }
91
+
92
+ // what GET /levels returns: the published levels, and a version that changes on every publish
93
+ export interface ILevelsConfig {
94
+ version: number;
95
+ levels: ILevelDefinition[];
96
+ awards: IXpAwards;
97
+ }
98
+
99
+ /**
100
+ * GET /levels?version=<the app's cached version>: the published configuration, or just `unchanged` when the app
101
+ * already has the current version, so unchanged configurations aren't re-downloaded on every launch.
102
+ */
103
+ export type LevelsResponseData = ILevelsConfig | { version: number, unchanged: true };
@@ -12,10 +12,14 @@ export interface IUserData {
12
12
  learningLanguage: Language,
13
13
  name: string,
14
14
  phone: string,
15
+ // Shown to the user and ranked on the leaderboard - performance-based. Not the same as xp (see below).
15
16
  rewardPoints: number,
16
17
  signUpDate: MySQLDate,
17
18
  testsCompletedCount: number,
18
19
  uiLanguage: Language,
19
20
  completedOnboarding: boolean,
20
- learningSet: number
21
+ learningSet: number,
22
+ // Experience points: internal, never shown to the user - they only decide the experience level. Not the same as
23
+ // rewardPoints (shown, performance-based, leaderboard). See concrete/level.ts.
24
+ xp: number
21
25
  }
package/src/index.ts CHANGED
@@ -1,9 +1,14 @@
1
+ export * from './concrete/color';
1
2
  export * from './concrete/date';
3
+ export * from './concrete/level';
4
+ export * from './concrete/levelDefaults';
5
+ export * from './concrete/levelValidation';
2
6
  export * from './concrete/lexeme';
3
7
  export * from './concrete/string';
4
8
  export * from './concrete/vocabCheck';
5
9
 
6
10
  export * from './design/api';
11
+ export * from './design/levels';
7
12
  export * from './design/lexemes';
8
13
  export * from './design/types';
9
14
  export * from './design/user';
@@ -0,0 +1,89 @@
1
+ import { expect } from 'chai';
2
+ import {
3
+ getBestStreak,
4
+ getFlashcardReviewXp,
5
+ getLevel,
6
+ getLevelProgress,
7
+ getTestXp,
8
+ LEVELS,
9
+ maxLevel,
10
+ } from '../src/concrete/level';
11
+
12
+ describe('levels', () => {
13
+ it('are numbered 1..n with rising thresholds and non-falling streak gates', () => {
14
+ LEVELS.forEach((level, i) => {
15
+ expect(level.level).to.equal(i + 1);
16
+ if (i > 0) {
17
+ expect(level.xpThreshold).to.be.above(LEVELS[i - 1].xpThreshold);
18
+ expect(level.minBestStreak).to.be.at.least(LEVELS[i - 1].minBestStreak);
19
+ }
20
+ });
21
+ expect(LEVELS[0].xpThreshold).to.equal(0);
22
+ });
23
+ });
24
+
25
+ describe('getLevel', () => {
26
+ it('starts everyone at level 1', () => {
27
+ expect(getLevel(0, 0)).to.equal(1);
28
+ });
29
+ it('changes exactly at the XP threshold', () => {
30
+ expect(getLevel(59, 0)).to.equal(1);
31
+ expect(getLevel(60, 0)).to.equal(2);
32
+ expect(getLevel(449, 0)).to.equal(3);
33
+ expect(getLevel(450, 0)).to.equal(4);
34
+ });
35
+ it('holds the user at the last level whose streak gate is met', () => {
36
+ expect(getLevel(5000, 6)).to.equal(4);
37
+ expect(getLevel(5000, 7)).to.equal(5);
38
+ expect(getLevel(5000, 30)).to.equal(8);
39
+ });
40
+ it('caps at the top level', () => {
41
+ expect(getLevel(1_000_000, 1000)).to.equal(maxLevel);
42
+ });
43
+ it('never goes down as XP and best streak grow', () => {
44
+ let previous = 1;
45
+ for (let xp = 0; xp <= 12000; xp += 50) {
46
+ const level = getLevel(xp, Math.floor(xp / 150));
47
+ expect(level).to.be.at.least(previous);
48
+ previous = level;
49
+ }
50
+ });
51
+ });
52
+
53
+ describe('getLevelProgress', () => {
54
+ it('reports XP still needed and progress through the level', () => {
55
+ expect(getLevelProgress(130, 0)).to.deep.equal({
56
+ level: 2, nextLevel: 3, xpToNextLevel: 70, xpProgress: 0.5, streakDaysToNextLevel: 0,
57
+ });
58
+ });
59
+ it('reports a missing streak once the XP is there', () => {
60
+ const progress = getLevelProgress(1000, 3);
61
+ expect(progress.level).to.equal(4);
62
+ expect(progress.xpToNextLevel).to.equal(0);
63
+ expect(progress.xpProgress).to.equal(1);
64
+ expect(progress.streakDaysToNextLevel).to.equal(4);
65
+ });
66
+ it('has no next level at the top', () => {
67
+ const progress = getLevelProgress(20000, 100);
68
+ expect(progress.level).to.equal(maxLevel);
69
+ expect(progress.nextLevel).to.equal(undefined);
70
+ expect(progress.xpProgress).to.equal(1);
71
+ });
72
+ });
73
+
74
+ describe('XP awards', () => {
75
+ it('flashcard review: base, mastered words and a capped streak-day bonus', () => {
76
+ expect(getFlashcardReviewXp(0, 0)).to.equal(10);
77
+ expect(getFlashcardReviewXp(2, 0)).to.equal(20);
78
+ expect(getFlashcardReviewXp(0, 5)).to.equal(15);
79
+ expect(getFlashcardReviewXp(0, 90)).to.equal(40);
80
+ });
81
+ it('test: base plus one per known answer', () => {
82
+ expect(getTestXp(0)).to.equal(15);
83
+ expect(getTestXp(12)).to.equal(27);
84
+ });
85
+ it('best streak takes the larger of high and current', () => {
86
+ expect(getBestStreak({ highStreakLength: 3, currentStreakLength: 5 })).to.equal(5);
87
+ expect(getBestStreak({ highStreakLength: 9, currentStreakLength: 2 })).to.equal(9);
88
+ });
89
+ });
@@ -0,0 +1,106 @@
1
+ import { expect } from 'chai';
2
+ import {
3
+ DEFAULT_LEVEL_DEFINITIONS,
4
+ DEFAULT_LEVELS_CONFIG,
5
+ DEFAULT_XP_AWARDS,
6
+ generatePalette,
7
+ getFlashcardReviewXp,
8
+ getLevel,
9
+ getLevelProgress,
10
+ getTestXp,
11
+ getUserLevelProgress,
12
+ hexToHsl,
13
+ hslToHex,
14
+ ILevelDefinition,
15
+ shiftHue,
16
+ validateLevelsConfig,
17
+ } from '../src';
18
+
19
+ const level = (n: number, xpThreshold: number, minBestStreak = 0): ILevelDefinition => ({
20
+ ...DEFAULT_LEVEL_DEFINITIONS[0],
21
+ level: n,
22
+ xpThreshold,
23
+ minBestStreak,
24
+ });
25
+
26
+ describe('colour helpers', () => {
27
+ it('round-trips hex through HSL', () => {
28
+ for (const hex of ['#f5831f', '#046591', '#ffffff', '#000000']) expect(hslToHex(hexToHsl(hex))).to.equal(hex);
29
+ });
30
+ it('rotates hue and leaves greys alone', () => {
31
+ expect(shiftHue('#ff0000', 120)).to.equal('#00ff00');
32
+ expect(shiftHue('#808080', 90)).to.equal('#808080');
33
+ });
34
+ });
35
+
36
+ describe('levels from a configuration', () => {
37
+ const three = [level(1, 0), level(2, 100), level(3, 300, 5)];
38
+
39
+ it('works out the level from any number of levels', () => {
40
+ expect(getLevel(99, 0, three)).to.equal(1);
41
+ expect(getLevel(100, 0, three)).to.equal(2);
42
+ expect(getLevel(1000, 4, three)).to.equal(2);
43
+ expect(getLevel(1000, 5, three)).to.equal(3);
44
+ });
45
+ it('copes with levels in any order', () => {
46
+ expect(getLevel(150, 0, [three[2], three[0], three[1]])).to.equal(2);
47
+ });
48
+ it('reports progress within a configured level', () => {
49
+ expect(getLevelProgress(200, 0, three)).to.deep.equal({
50
+ level: 2, nextLevel: 3, xpToNextLevel: 100, xpProgress: 0.5, streakDaysToNextLevel: 5,
51
+ });
52
+ expect(getUserLevelProgress({ xp: 500, highStreakLength: 9, currentStreakLength: 0 }, three).nextLevel)
53
+ .to.equal(undefined);
54
+ });
55
+ it('uses configured XP awards', () => {
56
+ const awards = { ...DEFAULT_XP_AWARDS, flashcardReview: 20, perWordRetired: 1, test: 5, perTestKnownAnswer: 2 };
57
+ expect(getFlashcardReviewXp(3, 0, awards)).to.equal(23);
58
+ expect(getTestXp(4, awards)).to.equal(13);
59
+ expect(getTestXp(4)).to.equal(19);
60
+ });
61
+ });
62
+
63
+ describe('default level definitions', () => {
64
+ it('are the 10 built-in levels and pass validation', () => {
65
+ expect(DEFAULT_LEVEL_DEFINITIONS).to.have.length(10);
66
+ expect(validateLevelsConfig(DEFAULT_LEVELS_CONFIG)).to.deep.equal([]);
67
+ });
68
+ it('keep level 1 in the original design colours', () => {
69
+ const palette = DEFAULT_LEVEL_DEFINITIONS[0].palette;
70
+ expect(palette.background).to.equal('#ece7e1');
71
+ expect(palette.brand).to.equal('#317a97');
72
+ expect(palette.accent).to.equal('#e37639');
73
+ expect(palette.iconHueShift).to.equal(0);
74
+ expect(DEFAULT_LEVEL_DEFINITIONS[0].avatar.alphaHueShift).to.equal(0);
75
+ });
76
+ it('generates a rotated palette for other hues', () => {
77
+ expect(generatePalette(208).brand).to.equal(shiftHue('#317a97', 180));
78
+ });
79
+ });
80
+
81
+ describe('validateLevelsConfig', () => {
82
+ const valid = () => ({ levels: [level(1, 0), level(2, 50)], awards: { ...DEFAULT_XP_AWARDS } });
83
+
84
+ it('accepts a valid configuration', () => {
85
+ expect(validateLevelsConfig(valid())).to.deep.equal([]);
86
+ });
87
+ it('rejects gaps, falling thresholds and a non-zero first level', () => {
88
+ expect(validateLevelsConfig({ ...valid(), levels: [level(1, 0), level(3, 50)] }).join())
89
+ .to.contain('no gaps');
90
+ expect(validateLevelsConfig({ ...valid(), levels: [level(1, 0), level(2, 0)] }).join())
91
+ .to.contain('more XP');
92
+ expect(validateLevelsConfig({ ...valid(), levels: [level(1, 10)] }).join()).to.contain('0 XP');
93
+ });
94
+ it('rejects bad colours, names, presets, Lottie and awards', () => {
95
+ const bad = level(1, 0);
96
+ bad.palette = { ...bad.palette, accent: 'orange' };
97
+ bad.names = { en: '', cz: 'x' };
98
+ bad.avatar = { alphaHueShift: 0, preset: { id: 'nope' as never, params: {} }, lottie: '{not json' };
99
+ const errors = validateLevelsConfig({ levels: [bad], awards: { ...DEFAULT_XP_AWARDS, test: -1 } }).join('\n');
100
+ expect(errors).to.contain('accent must be a hex colour');
101
+ expect(errors).to.contain('en name');
102
+ expect(errors).to.contain("unknown avatar preset 'nope'");
103
+ expect(errors).to.contain('not valid JSON');
104
+ expect(errors).to.contain('XP award test');
105
+ });
106
+ });