Compare commits
5
Commits
ce00bc84b5
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7a0934f83 | ||
|
|
e5cbc3e4d4 | ||
|
|
08983814b5 | ||
|
|
4c7ca94ee4 | ||
|
|
56f10f7c29 |
No files matched your search
@@ -148,6 +148,10 @@ type UpdateOneMock = jest.Mock<
|
||||
ExecQuery<AcknowledgedUpdate>,
|
||||
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
|
||||
>;
|
||||
type BulkWriteMock = jest.Mock<
|
||||
Promise<AcknowledgedUpdate>,
|
||||
[Array<Record<string, unknown>>]
|
||||
>;
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> {
|
||||
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||
@@ -156,12 +160,35 @@ function asRecord(value: unknown): Record<string, unknown> {
|
||||
return {};
|
||||
}
|
||||
|
||||
function findTimelineSet(updateRiotMatch: UpdateOneMock) {
|
||||
const timelineUpdate = updateRiotMatch.mock.calls.find(([, update]) =>
|
||||
function findTimelinePersistUpdate(updateRiotMatch: UpdateOneMock) {
|
||||
return updateRiotMatch.mock.calls.find(([, update]) =>
|
||||
Boolean(asRecord(asRecord(update).$set).timeline),
|
||||
);
|
||||
expect(timelineUpdate).toBeDefined();
|
||||
return asRecord(asRecord(timelineUpdate?.[1]).$set);
|
||||
}
|
||||
|
||||
function findTimelineDiscardUpdate(updateRiotMatch: UpdateOneMock) {
|
||||
return updateRiotMatch.mock.calls.find(([, update]) =>
|
||||
Object.prototype.hasOwnProperty.call(
|
||||
asRecord(asRecord(update).$unset),
|
||||
'timeline',
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function playerMatchFeatureBulkSet(
|
||||
bulkWritePlayerMatchFeature: BulkWriteMock,
|
||||
puuid = 'target-puuid',
|
||||
) {
|
||||
const operations = bulkWritePlayerMatchFeature.mock.calls.flatMap(
|
||||
([bulkWriteOperations]) => bulkWriteOperations,
|
||||
);
|
||||
const operation = operations.find((candidate) => {
|
||||
const updateOne = asRecord(candidate.updateOne);
|
||||
const filter = asRecord(updateOne.filter);
|
||||
return filter.puuid === puuid;
|
||||
});
|
||||
expect(operation).toBeDefined();
|
||||
return asRecord(asRecord(asRecord(operation?.updateOne).update).$set);
|
||||
}
|
||||
|
||||
function execResolved<T>(value: T): ExecQuery<T> {
|
||||
@@ -264,6 +291,7 @@ interface PipelineHarnessOptions {
|
||||
accountError?: Error;
|
||||
computeMetricBaselines?: jest.Mock;
|
||||
existingMatchRaw?: Record<string, unknown> | null;
|
||||
existingTargetFeatures?: PlayerMatchFeature[];
|
||||
existingTimeline?: Record<string, unknown>;
|
||||
findOneAccountResult?: Account | null;
|
||||
getMatch?: jest.Mock<Promise<Record<string, unknown>>, [string, string]>;
|
||||
@@ -313,6 +341,12 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) {
|
||||
const updatePlayerMatchFeature: UpdateOneMock = jest
|
||||
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
||||
.mockReturnValue(execResolved({ acknowledged: true }));
|
||||
const bulkWritePlayerMatchFeature: BulkWriteMock = jest
|
||||
.fn<Promise<AcknowledgedUpdate>, Parameters<BulkWriteMock>>()
|
||||
.mockResolvedValue({ acknowledged: true });
|
||||
const findPlayerMatchFeatures = jest
|
||||
.fn()
|
||||
.mockReturnValue(leanExecResolved(options.existingTargetFeatures ?? []));
|
||||
const updatePlayerProfile: UpdateOneMock = jest
|
||||
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
||||
.mockReturnValue(execResolved({ acknowledged: true }));
|
||||
@@ -327,6 +361,8 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) {
|
||||
updateOne: updateAnalysisJob,
|
||||
},
|
||||
playerMatchFeature: {
|
||||
bulkWrite: bulkWritePlayerMatchFeature,
|
||||
find: findPlayerMatchFeatures,
|
||||
updateOne: updatePlayerMatchFeature,
|
||||
},
|
||||
playerProfile: {
|
||||
@@ -388,7 +424,9 @@ function createPipelineHarness(options: PipelineHarnessOptions = {}) {
|
||||
|
||||
return {
|
||||
findOneAccount,
|
||||
findPlayerMatchFeatures,
|
||||
findOneRiotMatch,
|
||||
bulkWritePlayerMatchFeature,
|
||||
computeMetricBaselines,
|
||||
getMatchIds,
|
||||
getMatch,
|
||||
@@ -526,11 +564,11 @@ describe('AnalysisPipelineService', () => {
|
||||
it('fetches missing match details, stores features, builds a profile, and completes the job', async () => {
|
||||
const {
|
||||
findOneRiotMatch,
|
||||
bulkWritePlayerMatchFeature,
|
||||
getMatch,
|
||||
getMatchTimeline,
|
||||
service,
|
||||
updateAnalysisJob,
|
||||
updatePlayerMatchFeature,
|
||||
updatePlayerProfile,
|
||||
updateRiotMatch,
|
||||
} = createPipelineHarness();
|
||||
@@ -548,16 +586,17 @@ describe('AnalysisPipelineService', () => {
|
||||
queueId: 420,
|
||||
},
|
||||
});
|
||||
const timelineSet = findTimelineSet(updateRiotMatch);
|
||||
expect(timelineSet.timeline).toEqual(createTimelinePayload());
|
||||
expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date);
|
||||
expect(findTimelinePersistUpdate(updateRiotMatch)).toBeUndefined();
|
||||
|
||||
const playerMatchFeatureUpdate = updatePlayerMatchFeature.mock.calls[0][1];
|
||||
expect(playerMatchFeatureUpdate).toMatchObject({
|
||||
$set: {
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
matchId: 'KR_1',
|
||||
},
|
||||
expect(bulkWritePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
expect(bulkWritePlayerMatchFeature.mock.calls[0]?.[0]).toHaveLength(3);
|
||||
const playerMatchFeatureSet = playerMatchFeatureBulkSet(
|
||||
bulkWritePlayerMatchFeature,
|
||||
);
|
||||
expect(playerMatchFeatureSet).toMatchObject({
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
matchId: 'KR_1',
|
||||
puuid: 'target-puuid',
|
||||
});
|
||||
|
||||
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
|
||||
@@ -582,10 +621,10 @@ describe('AnalysisPipelineService', () => {
|
||||
it('processes a stored seed account through the shared match feature pipeline', async () => {
|
||||
const {
|
||||
findOneAccount,
|
||||
bulkWritePlayerMatchFeature,
|
||||
getMatchIds,
|
||||
service,
|
||||
updateAnalysisJob,
|
||||
updatePlayerMatchFeature,
|
||||
updatePlayerProfile,
|
||||
} = createPipelineHarness({
|
||||
findOneAccountResult: createStoredAccount({
|
||||
@@ -620,7 +659,7 @@ describe('AnalysisPipelineService', () => {
|
||||
queue: 420,
|
||||
regionalRoute: 'asia',
|
||||
});
|
||||
expect(updatePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
expect(bulkWritePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
|
||||
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
|
||||
expect(playerProfileUpdate).toMatchObject({
|
||||
@@ -650,17 +689,15 @@ describe('AnalysisPipelineService', () => {
|
||||
normalizationMethod: 'population-percentile',
|
||||
}),
|
||||
);
|
||||
const { service, updatePlayerMatchFeature, updatePlayerProfile } =
|
||||
const { bulkWritePlayerMatchFeature, service, updatePlayerProfile } =
|
||||
createPipelineHarness({
|
||||
normalizeFeature,
|
||||
});
|
||||
|
||||
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
||||
|
||||
expect(normalizeFeature).toHaveBeenCalledTimes(1);
|
||||
const featureSet = asRecord(
|
||||
asRecord(updatePlayerMatchFeature.mock.calls[0]?.[1]).$set,
|
||||
);
|
||||
expect(normalizeFeature).toHaveBeenCalledTimes(3);
|
||||
const featureSet = playerMatchFeatureBulkSet(bulkWritePlayerMatchFeature);
|
||||
expect(asRecord(featureSet.normalized).kda).toBe(0.42);
|
||||
expect(featureSet.normalizationMethod).toBe('population-percentile');
|
||||
|
||||
@@ -787,7 +824,7 @@ describe('AnalysisPipelineService', () => {
|
||||
getMatch,
|
||||
getMatchTimeline,
|
||||
service,
|
||||
updatePlayerMatchFeature,
|
||||
bulkWritePlayerMatchFeature,
|
||||
updateRiotMatch,
|
||||
} = createPipelineHarness({
|
||||
existingMatchRaw: createMatchPayload(),
|
||||
@@ -798,41 +835,88 @@ describe('AnalysisPipelineService', () => {
|
||||
|
||||
expect(getMatch).not.toHaveBeenCalled();
|
||||
expect(getMatchTimeline).not.toHaveBeenCalled();
|
||||
expect(
|
||||
updateRiotMatch.mock.calls.find(([, update]) =>
|
||||
Boolean(asRecord(asRecord(update).$set).timeline),
|
||||
),
|
||||
).toBeUndefined();
|
||||
expect(updatePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
expect(findTimelinePersistUpdate(updateRiotMatch)).toBeUndefined();
|
||||
expect(findTimelineDiscardUpdate(updateRiotMatch)).toBeDefined();
|
||||
expect(bulkWritePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('fetches a missing timeline for cached match details', async () => {
|
||||
const { getMatch, getMatchTimeline, service, updateRiotMatch } =
|
||||
createPipelineHarness({
|
||||
existingMatchRaw: createMatchPayload(),
|
||||
});
|
||||
it('uses a current precomputed target feature without fetching match details or timeline', async () => {
|
||||
const existingFeature = createStoredFeature({
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
normalized: { kda: 1 },
|
||||
vector: VECTOR_METRICS.map((metric) => (metric.id === 'kda' ? 1 : 0)),
|
||||
timelineProcessed: true,
|
||||
});
|
||||
const {
|
||||
bulkWritePlayerMatchFeature,
|
||||
findOneRiotMatch,
|
||||
findPlayerMatchFeatures,
|
||||
getMatch,
|
||||
getMatchTimeline,
|
||||
service,
|
||||
updatePlayerProfile,
|
||||
} = createPipelineHarness({
|
||||
existingTargetFeatures: [existingFeature],
|
||||
});
|
||||
|
||||
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
||||
|
||||
expect(findPlayerMatchFeatures).toHaveBeenCalledWith({
|
||||
matchId: { $in: ['KR_1'] },
|
||||
puuid: 'target-puuid',
|
||||
queueId: 420,
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
timelineProcessed: true,
|
||||
});
|
||||
expect(findOneRiotMatch).not.toHaveBeenCalled();
|
||||
expect(getMatch).not.toHaveBeenCalled();
|
||||
expect(getMatchTimeline).not.toHaveBeenCalled();
|
||||
expect(bulkWritePlayerMatchFeature).not.toHaveBeenCalled();
|
||||
|
||||
const playerProfileUpdate = updatePlayerProfile.mock.calls[0][1];
|
||||
expect(playerProfileUpdate).toMatchObject({
|
||||
$set: {
|
||||
puuid: 'target-puuid',
|
||||
sampleGameCount: 1,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('fetches but does not persist a missing timeline for cached match details', async () => {
|
||||
const {
|
||||
bulkWritePlayerMatchFeature,
|
||||
getMatch,
|
||||
getMatchTimeline,
|
||||
service,
|
||||
updateRiotMatch,
|
||||
} = createPipelineHarness({
|
||||
existingMatchRaw: createMatchPayload(),
|
||||
});
|
||||
|
||||
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
||||
|
||||
expect(getMatch).not.toHaveBeenCalled();
|
||||
expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia');
|
||||
const timelineSet = findTimelineSet(updateRiotMatch);
|
||||
expect(timelineSet.timeline).toEqual(createTimelinePayload());
|
||||
expect(timelineSet.timelineFetchedAt).toBeInstanceOf(Date);
|
||||
expect(findTimelinePersistUpdate(updateRiotMatch)).toBeUndefined();
|
||||
expect(bulkWritePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('refetches cached timeline data when it is malformed', async () => {
|
||||
const { getMatchTimeline, service, updateRiotMatch } =
|
||||
createPipelineHarness({
|
||||
existingMatchRaw: createMatchPayload(),
|
||||
existingTimeline: {},
|
||||
});
|
||||
const {
|
||||
bulkWritePlayerMatchFeature,
|
||||
getMatchTimeline,
|
||||
service,
|
||||
updateRiotMatch,
|
||||
} = createPipelineHarness({
|
||||
existingMatchRaw: createMatchPayload(),
|
||||
existingTimeline: {},
|
||||
});
|
||||
|
||||
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
||||
|
||||
expect(getMatchTimeline).toHaveBeenCalledWith('KR_1', 'asia');
|
||||
const timelineSet = findTimelineSet(updateRiotMatch);
|
||||
expect(timelineSet.timeline).toEqual(createTimelinePayload());
|
||||
expect(findTimelinePersistUpdate(updateRiotMatch)).toBeUndefined();
|
||||
expect(bulkWritePlayerMatchFeature).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stores derived timeline data when a timeline is available', async () => {
|
||||
@@ -894,15 +978,15 @@ describe('AnalysisPipelineService', () => {
|
||||
const getMatchTimeline = jest
|
||||
.fn<Promise<Record<string, unknown>>, [string, string]>()
|
||||
.mockResolvedValue(timeline);
|
||||
const { service, updatePlayerMatchFeature, updatePlayerProfile } =
|
||||
const { bulkWritePlayerMatchFeature, service, updatePlayerProfile } =
|
||||
createPipelineHarness({
|
||||
getMatchTimeline,
|
||||
});
|
||||
|
||||
await service.processUserAnalysisJob(createJobData(), 'analysis-job-1');
|
||||
|
||||
const playerMatchFeatureSet = asRecord(
|
||||
asRecord(updatePlayerMatchFeature.mock.calls[0][1]).$set,
|
||||
const playerMatchFeatureSet = playerMatchFeatureBulkSet(
|
||||
bulkWritePlayerMatchFeature,
|
||||
);
|
||||
const playerMatchFeatureSetFeatures = asRecord(
|
||||
playerMatchFeatureSet.features,
|
||||
|
||||
@@ -41,9 +41,15 @@ import { TimelineMetricService } from './timeline-metric.service';
|
||||
interface MatchRecord {
|
||||
matchId: string;
|
||||
raw: Record<string, unknown>;
|
||||
shouldDiscardStoredTimeline?: boolean;
|
||||
timeline?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface MatchFetchProgressOptions {
|
||||
initialFetchedMatches?: number;
|
||||
totalMatches?: number;
|
||||
}
|
||||
|
||||
interface ParsedMatchSummary {
|
||||
gameCreation: number;
|
||||
gameDuration: number;
|
||||
@@ -155,10 +161,32 @@ export class AnalysisPipelineService {
|
||||
return;
|
||||
}
|
||||
|
||||
const matchRecords = await this.fetchAndStoreMatches(
|
||||
const reusableFeaturesByMatchId = await this.findReusableMatchFeatures({
|
||||
matchIds,
|
||||
puuid: account.puuid,
|
||||
queueId: normalizedData.queueId,
|
||||
});
|
||||
const matchIdsRequiringFeatureExtraction = matchIds.filter(
|
||||
(matchId) => !reusableFeaturesByMatchId.has(matchId),
|
||||
);
|
||||
if (matchIdsRequiringFeatureExtraction.length === 0) {
|
||||
await this.updateJob(jobId, {
|
||||
progress: {
|
||||
fetchedMatches: matchIds.length,
|
||||
totalMatches: matchIds.length,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const matchRecords = await this.fetchAndStoreMatches(
|
||||
matchIdsRequiringFeatureExtraction,
|
||||
normalizedData,
|
||||
jobId,
|
||||
USER_ANALYSIS_JOB_NAME,
|
||||
{
|
||||
initialFetchedMatches: reusableFeaturesByMatchId.size,
|
||||
totalMatches: matchIds.length,
|
||||
},
|
||||
);
|
||||
await this.updateJob(jobId, {
|
||||
stage: 'extract-features',
|
||||
@@ -169,15 +197,20 @@ export class AnalysisPipelineService {
|
||||
account.puuid,
|
||||
normalizedData.queueId,
|
||||
);
|
||||
const profileFeatures = this.mergeProfileFeatures(
|
||||
matchIds,
|
||||
reusableFeaturesByMatchId,
|
||||
extractedFeatures,
|
||||
);
|
||||
await this.updateJob(jobId, {
|
||||
stage: 'build-profile',
|
||||
});
|
||||
|
||||
if (extractedFeatures.length > 0) {
|
||||
if (profileFeatures.length > 0) {
|
||||
await this.buildAndStoreProfile(
|
||||
account,
|
||||
normalizedData,
|
||||
extractedFeatures,
|
||||
profileFeatures,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -405,11 +438,36 @@ export class AnalysisPipelineService {
|
||||
};
|
||||
}
|
||||
|
||||
const matchRecords = await this.fetchAndStoreMatches(
|
||||
const reusableFeaturesByMatchId = await this.findReusableMatchFeatures({
|
||||
matchIds,
|
||||
puuid: account.puuid,
|
||||
queueId: normalizedData.queueId,
|
||||
});
|
||||
const matchIdsRequiringFeatureExtraction = matchIds.filter(
|
||||
(matchId) => !reusableFeaturesByMatchId.has(matchId),
|
||||
);
|
||||
if (matchIdsRequiringFeatureExtraction.length === 0) {
|
||||
await this.updateJob(
|
||||
jobId,
|
||||
{
|
||||
progress: {
|
||||
fetchedMatches: matchIds.length,
|
||||
totalMatches: matchIds.length,
|
||||
},
|
||||
},
|
||||
SEED_COLLECTION_JOB_NAME,
|
||||
);
|
||||
}
|
||||
|
||||
const matchRecords = await this.fetchAndStoreMatches(
|
||||
matchIdsRequiringFeatureExtraction,
|
||||
normalizedData,
|
||||
jobId,
|
||||
SEED_COLLECTION_JOB_NAME,
|
||||
{
|
||||
initialFetchedMatches: reusableFeaturesByMatchId.size,
|
||||
totalMatches: matchIds.length,
|
||||
},
|
||||
);
|
||||
await this.updateJob(
|
||||
jobId,
|
||||
@@ -424,6 +482,11 @@ export class AnalysisPipelineService {
|
||||
account.puuid,
|
||||
normalizedData.queueId,
|
||||
);
|
||||
const profileFeatures = this.mergeProfileFeatures(
|
||||
matchIds,
|
||||
reusableFeaturesByMatchId,
|
||||
extractedFeatures,
|
||||
);
|
||||
await this.updateJob(
|
||||
jobId,
|
||||
{
|
||||
@@ -432,19 +495,15 @@ export class AnalysisPipelineService {
|
||||
SEED_COLLECTION_JOB_NAME,
|
||||
);
|
||||
|
||||
if (extractedFeatures.length > 0) {
|
||||
await this.buildAndStoreProfile(
|
||||
account,
|
||||
normalizedData,
|
||||
extractedFeatures,
|
||||
);
|
||||
if (profileFeatures.length > 0) {
|
||||
await this.buildAndStoreProfile(account, normalizedData, profileFeatures);
|
||||
}
|
||||
|
||||
return {
|
||||
puuid: account.puuid,
|
||||
fetchedMatches: matchRecords.length,
|
||||
extractedFeatures: extractedFeatures.length,
|
||||
profileBuilt: extractedFeatures.length > 0,
|
||||
profileBuilt: profileFeatures.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -500,14 +559,72 @@ export class AnalysisPipelineService {
|
||||
return storedAccount;
|
||||
}
|
||||
|
||||
private async findReusableMatchFeatures(params: {
|
||||
matchIds: string[];
|
||||
puuid: string;
|
||||
queueId: number;
|
||||
}): Promise<Map<string, PlayerMatchFeature>> {
|
||||
if (params.matchIds.length === 0) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const playerMatchFeatureModel =
|
||||
await this.connectionService.getModel('playerMatchFeature');
|
||||
const features = await playerMatchFeatureModel
|
||||
.find({
|
||||
matchId: { $in: params.matchIds },
|
||||
puuid: params.puuid,
|
||||
queueId: params.queueId,
|
||||
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||
timelineProcessed: true,
|
||||
})
|
||||
.lean<PlayerMatchFeature[]>()
|
||||
.exec();
|
||||
|
||||
return new Map(
|
||||
features.map((feature) => [feature.matchId, feature] as const),
|
||||
);
|
||||
}
|
||||
|
||||
private mergeProfileFeatures(
|
||||
matchIds: string[],
|
||||
reusableFeaturesByMatchId: Map<string, PlayerMatchFeature>,
|
||||
extractedFeatures: ExtractedPlayerMatchFeature[],
|
||||
): Array<PlayerMatchFeature | ExtractedPlayerMatchFeature> {
|
||||
const extractedFeaturesByMatchId = new Map(
|
||||
extractedFeatures.map((feature) => [feature.matchId, feature] as const),
|
||||
);
|
||||
const profileFeatures: Array<
|
||||
PlayerMatchFeature | ExtractedPlayerMatchFeature
|
||||
> = [];
|
||||
|
||||
for (const matchId of matchIds) {
|
||||
const reusableFeature = reusableFeaturesByMatchId.get(matchId);
|
||||
if (reusableFeature) {
|
||||
profileFeatures.push(reusableFeature);
|
||||
continue;
|
||||
}
|
||||
|
||||
const extractedFeature = extractedFeaturesByMatchId.get(matchId);
|
||||
if (extractedFeature) {
|
||||
profileFeatures.push(extractedFeature);
|
||||
}
|
||||
}
|
||||
|
||||
return profileFeatures;
|
||||
}
|
||||
|
||||
private async fetchAndStoreMatches(
|
||||
matchIds: string[],
|
||||
data: Pick<UserAnalysisJobData, 'queueId' | 'regionalRoute'>,
|
||||
jobId: string,
|
||||
jobType = USER_ANALYSIS_JOB_NAME,
|
||||
progressOptions: MatchFetchProgressOptions = {},
|
||||
): Promise<MatchRecord[]> {
|
||||
const matchRecords: MatchRecord[] = [];
|
||||
const riotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const totalMatches = progressOptions.totalMatches ?? matchIds.length;
|
||||
const initialFetchedMatches = progressOptions.initialFetchedMatches ?? 0;
|
||||
|
||||
for (const [index, matchId] of matchIds.entries()) {
|
||||
try {
|
||||
@@ -518,7 +635,7 @@ export class AnalysisPipelineService {
|
||||
|
||||
if (existingMatch) {
|
||||
if (this.isEligibleMatch(existingMatch.raw, data.queueId)) {
|
||||
const timeline = await this.fetchAndStoreMissingTimeline(
|
||||
const timeline = await this.fetchMissingTimeline(
|
||||
matchId,
|
||||
existingMatch.timeline,
|
||||
data.regionalRoute,
|
||||
@@ -526,6 +643,7 @@ export class AnalysisPipelineService {
|
||||
matchRecords.push({
|
||||
matchId,
|
||||
raw: existingMatch.raw,
|
||||
shouldDiscardStoredTimeline: existingMatch.timeline !== undefined,
|
||||
...(timeline ? { timeline } : {}),
|
||||
});
|
||||
}
|
||||
@@ -536,7 +654,7 @@ export class AnalysisPipelineService {
|
||||
);
|
||||
await this.storeRiotMatch(matchId, rawMatch);
|
||||
if (this.isEligibleMatch(rawMatch, data.queueId)) {
|
||||
const timeline = await this.fetchAndStoreMissingTimeline(
|
||||
const timeline = await this.fetchMissingTimeline(
|
||||
matchId,
|
||||
undefined,
|
||||
data.regionalRoute,
|
||||
@@ -557,8 +675,8 @@ export class AnalysisPipelineService {
|
||||
jobId,
|
||||
{
|
||||
progress: {
|
||||
fetchedMatches: index + 1,
|
||||
totalMatches: matchIds.length,
|
||||
fetchedMatches: initialFetchedMatches + index + 1,
|
||||
totalMatches,
|
||||
},
|
||||
},
|
||||
jobType,
|
||||
@@ -596,7 +714,7 @@ export class AnalysisPipelineService {
|
||||
.exec();
|
||||
}
|
||||
|
||||
private async fetchAndStoreMissingTimeline(
|
||||
private async fetchMissingTimeline(
|
||||
matchId: string,
|
||||
existingTimeline: unknown,
|
||||
regionalRoute: UserAnalysisJobData['regionalRoute'],
|
||||
@@ -616,7 +734,6 @@ export class AnalysisPipelineService {
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
await this.storeRiotMatchTimeline(matchId, timeline);
|
||||
return timeline;
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
@@ -626,19 +743,16 @@ export class AnalysisPipelineService {
|
||||
}
|
||||
}
|
||||
|
||||
private async storeRiotMatchTimeline(
|
||||
matchId: string,
|
||||
timeline: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
private async discardStoredMatchTimeline(matchId: string): Promise<void> {
|
||||
const riotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
|
||||
await riotMatchModel
|
||||
.updateOne(
|
||||
{ matchId },
|
||||
{ matchId, timeline: { $exists: true } },
|
||||
{
|
||||
$set: {
|
||||
timeline,
|
||||
timelineFetchedAt: new Date(),
|
||||
$unset: {
|
||||
timeline: '',
|
||||
timelineFetchedAt: '',
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -650,22 +764,62 @@ export class AnalysisPipelineService {
|
||||
puuid: string,
|
||||
queueId: number,
|
||||
): Promise<ExtractedPlayerMatchFeature[]> {
|
||||
const playerMatchFeatureModel =
|
||||
await this.connectionService.getModel('playerMatchFeature');
|
||||
const extractedFeatures: ExtractedPlayerMatchFeature[] = [];
|
||||
|
||||
for (const matchRecord of matchRecords) {
|
||||
try {
|
||||
const participantPuuids = matchRecord.timeline
|
||||
? this.resolveMatchParticipantPuuids(matchRecord.raw)
|
||||
: [puuid];
|
||||
const matchFeatures = await this.extractMatchParticipantFeatures(
|
||||
matchRecord,
|
||||
participantPuuids,
|
||||
queueId,
|
||||
);
|
||||
await this.storePlayerMatchFeatures(matchFeatures);
|
||||
if (matchRecord.shouldDiscardStoredTimeline === true) {
|
||||
await this.discardStoredMatchTimeline(matchRecord.matchId);
|
||||
}
|
||||
|
||||
const targetFeature = matchFeatures.find(
|
||||
(feature) => feature.puuid === puuid,
|
||||
);
|
||||
if (targetFeature) {
|
||||
extractedFeatures.push(targetFeature);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Skipping feature extraction for matchId="${this.safeLogText(matchRecord.matchId)}": ${this.safeLogText(errorMessage(error))}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return extractedFeatures;
|
||||
}
|
||||
|
||||
private async extractMatchParticipantFeatures(
|
||||
matchRecord: MatchRecord,
|
||||
participantPuuids: string[],
|
||||
queueId: number,
|
||||
): Promise<ExtractedPlayerMatchFeature[]> {
|
||||
const features: ExtractedPlayerMatchFeature[] = [];
|
||||
const uniqueParticipantPuuids = [...new Set(participantPuuids)];
|
||||
const derived = matchRecord.timeline
|
||||
? this.timelineDerivedService.buildDerivedData(
|
||||
matchRecord.timeline,
|
||||
matchRecord.raw,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
for (const participantPuuid of uniqueParticipantPuuids) {
|
||||
try {
|
||||
const feature = this.featureExtractorService.extractPlayerMatchFeature(
|
||||
matchRecord.raw,
|
||||
puuid,
|
||||
participantPuuid,
|
||||
);
|
||||
if (feature.queueId !== queueId) continue;
|
||||
if (matchRecord.timeline) {
|
||||
const derived = this.timelineDerivedService.buildDerivedData(
|
||||
matchRecord.timeline,
|
||||
matchRecord.raw,
|
||||
);
|
||||
|
||||
if (matchRecord.timeline && derived) {
|
||||
const timelineMetrics =
|
||||
this.timelineMetricService.extractTimelineMetrics(
|
||||
feature,
|
||||
@@ -688,27 +842,57 @@ export class AnalysisPipelineService {
|
||||
feature.timelineProcessed = true;
|
||||
}
|
||||
|
||||
const normalizedFeature = await this.normalizeExtractedFeature(feature);
|
||||
|
||||
await playerMatchFeatureModel
|
||||
.updateOne(
|
||||
{
|
||||
matchId: normalizedFeature.matchId,
|
||||
puuid: normalizedFeature.puuid,
|
||||
},
|
||||
{ $set: normalizedFeature },
|
||||
{ upsert: true },
|
||||
)
|
||||
.exec();
|
||||
extractedFeatures.push(normalizedFeature);
|
||||
features.push(await this.normalizeExtractedFeature(feature));
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
`Skipping feature extraction for matchId="${this.safeLogText(matchRecord.matchId)}": ${this.safeLogText(errorMessage(error))}`,
|
||||
`Skipping feature extraction for matchId="${this.safeLogText(matchRecord.matchId)}" puuid="${this.safeLogText(participantPuuid)}": ${this.safeLogText(errorMessage(error))}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return extractedFeatures;
|
||||
return features;
|
||||
}
|
||||
|
||||
private async storePlayerMatchFeatures(
|
||||
features: ExtractedPlayerMatchFeature[],
|
||||
): Promise<void> {
|
||||
if (features.length === 0) return;
|
||||
|
||||
const playerMatchFeatureModel =
|
||||
await this.connectionService.getModel('playerMatchFeature');
|
||||
await playerMatchFeatureModel.bulkWrite(
|
||||
features.map((feature) => ({
|
||||
updateOne: {
|
||||
filter: {
|
||||
matchId: feature.matchId,
|
||||
puuid: feature.puuid,
|
||||
},
|
||||
update: {
|
||||
$set: feature,
|
||||
},
|
||||
upsert: true,
|
||||
},
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
private resolveMatchParticipantPuuids(
|
||||
rawMatch: Record<string, unknown>,
|
||||
): string[] {
|
||||
const info = asRecord(rawMatch.info);
|
||||
const participants = Array.isArray(info.participants)
|
||||
? info.participants
|
||||
: [];
|
||||
const participantPuuids = participants
|
||||
.map((participant) => asString(asRecord(participant).puuid))
|
||||
.filter((participantPuuid): participantPuuid is string =>
|
||||
Boolean(participantPuuid),
|
||||
);
|
||||
|
||||
if (participantPuuids.length > 0) {
|
||||
return participantPuuids;
|
||||
}
|
||||
return this.parseMatchSummary(rawMatch).participantPuuids;
|
||||
}
|
||||
|
||||
private async normalizeExtractedFeature(
|
||||
@@ -863,10 +1047,10 @@ export class AnalysisPipelineService {
|
||||
private async buildAndStoreProfile(
|
||||
account: Account,
|
||||
data: Pick<UserAnalysisJobData, 'queueId'>,
|
||||
extractedFeatures: ExtractedPlayerMatchFeature[],
|
||||
profileFeatures: Array<PlayerMatchFeature | ExtractedPlayerMatchFeature>,
|
||||
): Promise<void> {
|
||||
await this.storeBuiltProfile({
|
||||
features: extractedFeatures,
|
||||
features: profileFeatures,
|
||||
isSeed: account.isSeed,
|
||||
tierInfo: this.resolveRankedSoloTier(account),
|
||||
puuid: account.puuid,
|
||||
@@ -929,7 +1113,7 @@ export class AnalysisPipelineService {
|
||||
}
|
||||
|
||||
private async storeBuiltProfile(params: {
|
||||
features: PlayerMatchFeature[] | ExtractedPlayerMatchFeature[];
|
||||
features: Array<PlayerMatchFeature | ExtractedPlayerMatchFeature>;
|
||||
isSeed: boolean;
|
||||
tierInfo?: TierInfo;
|
||||
puuid: string;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Post,
|
||||
Query,
|
||||
Req,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import type {
|
||||
AnalysisJobStatusDto,
|
||||
@@ -20,6 +21,8 @@ import {
|
||||
toRegionalRoute,
|
||||
type RiotPlatformRoute,
|
||||
} from '../riot/riot.types';
|
||||
import { SecretService } from '../global/secret/secret.service';
|
||||
import { SEED_SOURCES, type SeedSource } from '../global/database/schemas';
|
||||
import { AnalysisQueueService } from './analysis-queue.service';
|
||||
import {
|
||||
DEFAULT_ANALYSIS_MATCH_COUNT,
|
||||
@@ -28,8 +31,14 @@ import {
|
||||
} from './analysis.constants';
|
||||
import { AnalysisReadService } from './analysis-read.service';
|
||||
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
|
||||
import type { UserAnalysisJobData } from './analysis.types';
|
||||
import type {
|
||||
SeedCollectionJobData,
|
||||
UserAnalysisJobData,
|
||||
} from './analysis.types';
|
||||
import type { Request } from 'express';
|
||||
import { createHash, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
const MAX_ADMIN_SEED_COLLECTION_SOURCE_LIMIT = 200;
|
||||
|
||||
@Controller()
|
||||
export class AnalysisController {
|
||||
@@ -37,6 +46,7 @@ export class AnalysisController {
|
||||
private readonly analysisQueueService: AnalysisQueueService,
|
||||
private readonly analysisReadService: AnalysisReadService,
|
||||
private readonly analysisRequestThrottleService: AnalysisRequestThrottleService,
|
||||
private readonly secretService: SecretService,
|
||||
) {}
|
||||
|
||||
@Post('analysis/request')
|
||||
@@ -52,6 +62,18 @@ export class AnalysisController {
|
||||
return this.analysisQueueService.enqueueUserAnalysis(data);
|
||||
}
|
||||
|
||||
@Post('admin/seed-collection/request')
|
||||
@HttpCode(202)
|
||||
public async requestSeedCollection(
|
||||
@Body() body: unknown,
|
||||
@Req() request: Request,
|
||||
): Promise<AnalysisRequestAcceptedDto> {
|
||||
await this.assertAdminRequest(request);
|
||||
return this.analysisQueueService.enqueueSeedCollection(
|
||||
this.parseSeedCollectionRequest(body),
|
||||
);
|
||||
}
|
||||
|
||||
@Get('analysis/jobs/:jobId')
|
||||
public async getJobStatus(
|
||||
@Param('jobId') jobId: string,
|
||||
@@ -105,6 +127,19 @@ export class AnalysisController {
|
||||
};
|
||||
}
|
||||
|
||||
private parseSeedCollectionRequest(body: unknown): SeedCollectionJobData {
|
||||
const record = body === undefined ? {} : this.requireRecord(body);
|
||||
const platformRoute = this.parsePlatformRoute(record.platform ?? 'kr');
|
||||
const queueId = this.parseSeedCollectionQueueId(record.queueId);
|
||||
const sourceLimits = this.parseSeedSourceLimits(record.sourceLimits);
|
||||
|
||||
return {
|
||||
platformRoute,
|
||||
queueId,
|
||||
...(sourceLimits ? { sourceLimits } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
private requireRecord(value: unknown): Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw new BadRequestException('Request body must be an object.');
|
||||
@@ -165,6 +200,18 @@ export class AnalysisController {
|
||||
return queueId;
|
||||
}
|
||||
|
||||
private parseSeedCollectionQueueId(value: unknown): number {
|
||||
if (value === undefined) return 420;
|
||||
if (
|
||||
typeof value !== 'number' ||
|
||||
!Number.isInteger(value) ||
|
||||
value !== 420
|
||||
) {
|
||||
throw new BadRequestException('queueId is unsupported.');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private parseSimilarPlayersLimit(value?: string): number {
|
||||
if (value === undefined) return 10;
|
||||
const limit = Number(value);
|
||||
@@ -174,7 +221,73 @@ export class AnalysisController {
|
||||
return Math.min(limit, 10);
|
||||
}
|
||||
|
||||
private parseSeedSourceLimits(
|
||||
value: unknown,
|
||||
): Partial<Record<SeedSource, number>> | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||
throw new BadRequestException('sourceLimits must be an object.');
|
||||
}
|
||||
|
||||
const sourceLimits: Partial<Record<SeedSource, number>> = {};
|
||||
for (const [source, limit] of Object.entries(value)) {
|
||||
if (!SEED_SOURCES.includes(source as SeedSource)) {
|
||||
throw new BadRequestException(`sourceLimits.${source} is unsupported.`);
|
||||
}
|
||||
if (
|
||||
typeof limit !== 'number' ||
|
||||
!Number.isInteger(limit) ||
|
||||
limit < 0 ||
|
||||
limit > MAX_ADMIN_SEED_COLLECTION_SOURCE_LIMIT
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
`sourceLimits.${source} must be an integer between 0 and ${MAX_ADMIN_SEED_COLLECTION_SOURCE_LIMIT}.`,
|
||||
);
|
||||
}
|
||||
sourceLimits[source as SeedSource] = limit;
|
||||
}
|
||||
|
||||
return sourceLimits;
|
||||
}
|
||||
|
||||
private resolveClientKey(request: Request): string {
|
||||
return request.ip || request.socket.remoteAddress || 'unknown-client';
|
||||
}
|
||||
|
||||
private async assertAdminRequest(request: Request): Promise<void> {
|
||||
const actualToken = this.extractBearerToken(request);
|
||||
if (!actualToken) {
|
||||
throw new UnauthorizedException('Admin token is required.');
|
||||
}
|
||||
|
||||
let expectedToken: string;
|
||||
try {
|
||||
expectedToken = await this.secretService.get<string>('ADMIN_API_TOKEN');
|
||||
} catch {
|
||||
throw new UnauthorizedException('Admin token is not configured.');
|
||||
}
|
||||
|
||||
if (!this.secureTokenEquals(actualToken, expectedToken)) {
|
||||
throw new UnauthorizedException('Admin token is invalid.');
|
||||
}
|
||||
}
|
||||
|
||||
private extractBearerToken(request: Request): string | null {
|
||||
const authorization = request.headers.authorization;
|
||||
if (!authorization) return null;
|
||||
const match = authorization.match(/^Bearer\s+(.+)$/i);
|
||||
return match ? match[1]?.trim() || null : null;
|
||||
}
|
||||
|
||||
private secureTokenEquals(
|
||||
actualToken: string,
|
||||
expectedToken: string,
|
||||
): boolean {
|
||||
if (expectedToken.length === 0) return false;
|
||||
const actualHash = createHash('sha256').update(actualToken).digest();
|
||||
const expectedHash = createHash('sha256').update(expectedToken).digest();
|
||||
return timingSafeEqual(actualHash, expectedHash);
|
||||
}
|
||||
}
|
||||
@@ -276,6 +276,39 @@ describe('SimilarPlayerService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('recomputes when the cached similar-player result is empty', async () => {
|
||||
const currentProfile = createProfile();
|
||||
const candidateProfile = createProfile({
|
||||
puuid: 'newly-indexed-similar-player',
|
||||
score: 0.92,
|
||||
});
|
||||
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
||||
const aggregate = jest.fn(() => createAggregateExec([candidateProfile]));
|
||||
const recommendationFindOne = jest.fn(() =>
|
||||
createSortedLeanExec({
|
||||
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||
result: { matches: [] },
|
||||
}),
|
||||
);
|
||||
const updateOne = jest.fn(() => createUpdateExec({ acknowledged: true }));
|
||||
const service = new SimilarPlayerService({
|
||||
getModel: jest.fn((modelKey: string) =>
|
||||
Promise.resolve(
|
||||
modelKey === 'playerProfile'
|
||||
? { findOne, aggregate }
|
||||
: { findOne: recommendationFindOne, updateOne },
|
||||
),
|
||||
),
|
||||
} as unknown as ConnectionService);
|
||||
|
||||
const result = await service.findSimilarPlayers('target-puuid', 420, 10);
|
||||
|
||||
expect(aggregate).toHaveBeenCalledTimes(1);
|
||||
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||
expect(result.matches).toHaveLength(1);
|
||||
expect(result.matches[0]?.puuid).toBe('newly-indexed-similar-player');
|
||||
});
|
||||
|
||||
it('returns a fresh cached similar-player recommendation without running vector search', async () => {
|
||||
const currentProfile = createProfile();
|
||||
const cachedMatch = {
|
||||
|
||||
@@ -427,6 +427,7 @@ export class SimilarPlayerService {
|
||||
): SimilarPlayer[] | null {
|
||||
const matches = recommendation?.result?.matches;
|
||||
if (!Array.isArray(matches)) return null;
|
||||
if (matches.length === 0) return null;
|
||||
if (!matches.every((match) => this.isCachedSimilarPlayer(match))) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ describe('AppController (e2e)', () => {
|
||||
let app: INestApplication<App>;
|
||||
let analysisQueueService: {
|
||||
enqueueUserAnalysis: jest.Mock;
|
||||
enqueueSeedCollection: jest.Mock;
|
||||
};
|
||||
let similarPlayerService: {
|
||||
findSimilarPlayers: jest.Mock;
|
||||
@@ -43,6 +44,7 @@ describe('AppController (e2e)', () => {
|
||||
beforeEach(async () => {
|
||||
analysisQueueService = {
|
||||
enqueueUserAnalysis: jest.fn(),
|
||||
enqueueSeedCollection: jest.fn(),
|
||||
};
|
||||
similarPlayerService = {
|
||||
findSimilarPlayers: jest.fn(),
|
||||
@@ -65,6 +67,9 @@ describe('AppController (e2e)', () => {
|
||||
if (key === 'REDIS_URL') {
|
||||
return Promise.resolve('redis://localhost:6379/0');
|
||||
}
|
||||
if (key === 'ADMIN_API_TOKEN') {
|
||||
return Promise.resolve('admin-token');
|
||||
}
|
||||
return Promise.resolve('');
|
||||
}),
|
||||
ready: jest.fn().mockResolvedValue(undefined),
|
||||
@@ -198,6 +203,72 @@ describe('AppController (e2e)', () => {
|
||||
.expect(429);
|
||||
});
|
||||
|
||||
it('/api/admin/seed-collection/request (POST) validates admin token and enqueues seed collection', async () => {
|
||||
analysisQueueService.enqueueSeedCollection.mockResolvedValue({
|
||||
jobId: 'seed-job-1',
|
||||
status: 'queued',
|
||||
});
|
||||
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/admin/seed-collection/request')
|
||||
.set('Authorization', 'Bearer admin-token')
|
||||
.send({
|
||||
platform: 'kr',
|
||||
sourceLimits: {
|
||||
challenger: 0,
|
||||
grandmaster: 25,
|
||||
master: 0,
|
||||
},
|
||||
})
|
||||
.expect(202)
|
||||
.expect({
|
||||
jobId: 'seed-job-1',
|
||||
status: 'queued',
|
||||
});
|
||||
|
||||
expect(analysisQueueService.enqueueSeedCollection).toHaveBeenCalledWith({
|
||||
platformRoute: 'kr',
|
||||
queueId: 420,
|
||||
sourceLimits: {
|
||||
challenger: 0,
|
||||
grandmaster: 25,
|
||||
master: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('/api/admin/seed-collection/request (POST) rejects missing admin token', async () => {
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/admin/seed-collection/request')
|
||||
.send({
|
||||
sourceLimits: {
|
||||
grandmaster: 25,
|
||||
},
|
||||
})
|
||||
.expect(401);
|
||||
|
||||
expect(analysisQueueService.enqueueSeedCollection).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['unsupported source', { sourceLimits: { diamond: 10 } }],
|
||||
['negative source limit', { sourceLimits: { grandmaster: -1 } }],
|
||||
['fractional source limit', { sourceLimits: { grandmaster: 1.5 } }],
|
||||
['oversized source limit', { sourceLimits: { grandmaster: 201 } }],
|
||||
['unsupported queue', { queueId: 440 }],
|
||||
])(
|
||||
'/api/admin/seed-collection/request (POST) rejects %s',
|
||||
async (_label, body) => {
|
||||
await request(app.getHttpServer())
|
||||
.post('/api/admin/seed-collection/request')
|
||||
.set('Authorization', 'Bearer admin-token')
|
||||
.send(body)
|
||||
.expect(400);
|
||||
|
||||
expect(analysisQueueService.enqueueSeedCollection).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('/api/analysis/jobs/:jobId (GET) returns job statuses', async () => {
|
||||
const records = new Map([
|
||||
[
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
|
||||
```
|
||||
@@ -19,4 +19,12 @@ export default defineConfig([
|
||||
globals: globals.browser,
|
||||
},
|
||||
},
|
||||
{
|
||||
// StyleSeed 엔진 (벤더 코드) — shadcn식 variant export·matchMedia 구독 패턴 허용
|
||||
files: ['src/components/ui/**', 'src/motion/**'],
|
||||
rules: {
|
||||
'react-refresh/only-export-components': 'off',
|
||||
'react-hooks/set-state-in-effect': 'off',
|
||||
},
|
||||
},
|
||||
])
|
||||
+2
-2
@@ -4,8 +4,8 @@
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>persona-lenz</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<title>PersonaLenz</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
+28
-1
@@ -12,13 +12,39 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@persona-lenz/shared": "workspace:*",
|
||||
"@radix-ui/react-accordion": "^1.2.3",
|
||||
"@radix-ui/react-avatar": "^1.1.3",
|
||||
"@radix-ui/react-checkbox": "^1.1.4",
|
||||
"@radix-ui/react-dialog": "^1.1.6",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.6",
|
||||
"@radix-ui/react-label": "^2.1.2",
|
||||
"@radix-ui/react-popover": "^1.1.6",
|
||||
"@radix-ui/react-progress": "^1.1.2",
|
||||
"@radix-ui/react-radio-group": "^1.2.3",
|
||||
"@radix-ui/react-scroll-area": "^1.2.3",
|
||||
"@radix-ui/react-select": "^2.1.6",
|
||||
"@radix-ui/react-separator": "^1.1.2",
|
||||
"@radix-ui/react-slot": "^1.1.2",
|
||||
"@radix-ui/react-switch": "^1.1.3",
|
||||
"@radix-ui/react-tabs": "^1.1.3",
|
||||
"@radix-ui/react-toggle": "^1.1.2",
|
||||
"@radix-ui/react-toggle-group": "^1.1.2",
|
||||
"@radix-ui/react-tooltip": "^1.1.8",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"framer-motion": "^12.23.0",
|
||||
"lucide-react": "^0.487.0",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-hook-form": "^7.55.0",
|
||||
"react-router-dom": "^7.18.1",
|
||||
"recharts": "^3.9.1"
|
||||
"recharts": "^3.9.1",
|
||||
"tailwind-merge": "^3.2.0",
|
||||
"tw-animate-css": "^1.3.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tailwindcss/vite": "^4.1.0",
|
||||
"@types/node": "^24.13.2",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
@@ -27,6 +53,7 @@
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.3",
|
||||
"globals": "^17.7.0",
|
||||
"tailwindcss": "^4.1.0",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.62.0",
|
||||
"vite": "^8.1.1"
|
||||
|
||||
@@ -1,720 +0,0 @@
|
||||
.app-shell {
|
||||
min-height: 100svh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.app-header {
|
||||
min-height: 72px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 24px;
|
||||
padding: 0 32px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: color-mix(in srgb, var(--surface) 86%, transparent);
|
||||
backdrop-filter: blur(14px);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.brand {
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
color: var(--text-strong);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.brand-mark {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
display: inline-grid;
|
||||
place-items: center;
|
||||
border: 1px solid var(--accent);
|
||||
border-radius: 8px;
|
||||
color: var(--accent);
|
||||
font-size: 13px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.brand-copy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.brand-copy strong,
|
||||
.brand-copy span {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.brand-copy strong {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.brand-copy span {
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.header-status,
|
||||
.status-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
min-height: 28px;
|
||||
max-width: 100%;
|
||||
padding: 0 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.app-main {
|
||||
width: min(1180px, calc(100% - 32px));
|
||||
flex: 1;
|
||||
margin: 0 auto;
|
||||
padding: 48px 0;
|
||||
}
|
||||
|
||||
.riot-disclaimer {
|
||||
padding: 18px 32px 24px;
|
||||
border-top: 1px solid var(--border);
|
||||
color: var(--text-subtle);
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.home-view {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.1fr) minmax(360px, 0.9fr);
|
||||
gap: 32px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.home-copy,
|
||||
.analysis-form,
|
||||
.progress-panel,
|
||||
.chart-section,
|
||||
.champion-section,
|
||||
.insight-section,
|
||||
.similar-section,
|
||||
.dashboard-summary {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.home-copy {
|
||||
min-height: 430px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
padding: 36px;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
margin: 0 0 12px;
|
||||
color: var(--accent);
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.lead-copy {
|
||||
max-width: 740px;
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.home-facts {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin: 36px 0 0;
|
||||
}
|
||||
|
||||
.home-facts div,
|
||||
.summary-stat {
|
||||
min-width: 0;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.home-facts dt,
|
||||
.summary-stat span,
|
||||
.progress-meta span,
|
||||
.champion-copy span {
|
||||
display: block;
|
||||
color: var(--text-subtle);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
line-height: 1.4;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.home-facts dd,
|
||||
.summary-stat strong,
|
||||
.progress-meta strong {
|
||||
display: block;
|
||||
margin: 6px 0 0;
|
||||
color: var(--text-strong);
|
||||
font-size: 15px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.analysis-form {
|
||||
display: grid;
|
||||
gap: 18px;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.form-header,
|
||||
.section-heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.field {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.field span {
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.field input {
|
||||
width: 100%;
|
||||
min-height: 48px;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-soft);
|
||||
color: var(--text-strong);
|
||||
font: inherit;
|
||||
outline: none;
|
||||
padding: 0 14px;
|
||||
}
|
||||
|
||||
.field input:focus {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 24%, transparent);
|
||||
}
|
||||
|
||||
.primary-action,
|
||||
.secondary-action {
|
||||
min-height: 44px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
font-weight: 800;
|
||||
text-decoration: none;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.primary-action {
|
||||
background: var(--accent);
|
||||
color: #07110e;
|
||||
padding: 0 18px;
|
||||
}
|
||||
|
||||
.primary-action:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.secondary-action {
|
||||
border-color: var(--border-strong);
|
||||
background: var(--surface-soft);
|
||||
color: var(--text-strong);
|
||||
padding: 0 16px;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin: 0;
|
||||
border-radius: 8px;
|
||||
padding: 12px 14px;
|
||||
font-size: 14px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.message-error {
|
||||
border: 1px solid color-mix(in srgb, var(--danger) 52%, var(--border));
|
||||
background: color-mix(in srgb, var(--danger) 13%, var(--surface));
|
||||
color: var(--danger-strong);
|
||||
}
|
||||
|
||||
.message-warning {
|
||||
border: 1px solid color-mix(in srgb, var(--warning) 52%, var(--border));
|
||||
background: color-mix(in srgb, var(--warning) 13%, var(--surface));
|
||||
color: var(--warning-strong);
|
||||
}
|
||||
|
||||
.progress-view {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
min-height: calc(100svh - 240px);
|
||||
}
|
||||
|
||||
.progress-panel {
|
||||
width: min(760px, 100%);
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
.progress-meter {
|
||||
height: 12px;
|
||||
margin: 28px 0 18px;
|
||||
overflow: hidden;
|
||||
border-radius: 999px;
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.progress-meter span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
border-radius: inherit;
|
||||
background: var(--accent);
|
||||
transition: width 200ms ease;
|
||||
}
|
||||
|
||||
.progress-meta {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
.progress-meta div {
|
||||
min-width: 0;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.action-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.dashboard-view {
|
||||
display: grid;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.dashboard-summary {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1.2fr) minmax(360px, 0.8fr);
|
||||
gap: 28px;
|
||||
align-items: end;
|
||||
padding: 28px;
|
||||
}
|
||||
|
||||
.summary-stat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.chart-section,
|
||||
.champion-section,
|
||||
.insight-section,
|
||||
.similar-section {
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.radar-frame {
|
||||
min-height: 380px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.insight-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.metric-card-list {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr;
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.metric-card {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-soft);
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.metric-card-heading {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: start;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.metric-card-heading h3 {
|
||||
min-width: 0;
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.metric-card-heading strong {
|
||||
flex: 0 0 auto;
|
||||
color: var(--text-strong);
|
||||
font-size: 22px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.metric-card p {
|
||||
margin: 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.metric-card > span {
|
||||
color: var(--text-muted);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.champion-list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.champion-row {
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface-soft);
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.champion-icon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
flex: 0 0 44px;
|
||||
border-radius: 8px;
|
||||
background: var(--border);
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.champion-placeholder {
|
||||
display: inline-block;
|
||||
border: 1px solid var(--border-strong);
|
||||
}
|
||||
|
||||
.champion-copy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.champion-copy strong {
|
||||
overflow: hidden;
|
||||
color: var(--text-strong);
|
||||
font-size: 15px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.section-copy {
|
||||
margin: 8px 0 0;
|
||||
color: var(--text-muted);
|
||||
font-size: 14px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.similar-message {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.similar-table-wrap {
|
||||
margin-top: 18px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.similar-table-wrap:focus-visible {
|
||||
outline: 3px solid color-mix(in srgb, var(--accent) 42%, transparent);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
.similar-table {
|
||||
width: 100%;
|
||||
min-width: 780px;
|
||||
border-collapse: separate;
|
||||
border-spacing: 0 10px;
|
||||
}
|
||||
|
||||
.similar-table th {
|
||||
padding: 0 12px;
|
||||
color: var(--text-subtle);
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
line-height: 1.3;
|
||||
text-align: left;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.similar-table td {
|
||||
min-width: 0;
|
||||
padding: 14px 12px;
|
||||
border-block: 1px solid var(--border);
|
||||
background: var(--surface-soft);
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.similar-table td:first-child {
|
||||
border-left: 1px solid var(--border);
|
||||
border-radius: 8px 0 0 8px;
|
||||
}
|
||||
|
||||
.similar-table td:last-child {
|
||||
border-right: 1px solid var(--border);
|
||||
border-radius: 0 8px 8px 0;
|
||||
}
|
||||
|
||||
.similar-player,
|
||||
.similar-score,
|
||||
.similar-metric-groups,
|
||||
.similar-metric-group {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.similar-player strong,
|
||||
.similar-score strong,
|
||||
.similar-chip strong {
|
||||
overflow: hidden;
|
||||
color: var(--text-strong);
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.similar-player span,
|
||||
.similar-score span,
|
||||
.similar-chip span,
|
||||
.similar-metric-group > span,
|
||||
.similar-empty {
|
||||
color: var(--text-subtle);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.similar-score strong {
|
||||
font-size: 22px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.similar-chip-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.similar-chip {
|
||||
max-width: 100%;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
padding: 5px 8px;
|
||||
}
|
||||
|
||||
.similar-chip strong {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.similar-chip span {
|
||||
flex: 0 0 auto;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.similar-chip-accent {
|
||||
border-color: color-mix(in srgb, var(--accent) 48%, var(--border));
|
||||
}
|
||||
|
||||
.similar-chip-muted {
|
||||
background: color-mix(in srgb, var(--surface) 74%, var(--surface-soft));
|
||||
}
|
||||
|
||||
.similar-tier-badge {
|
||||
justify-self: start;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 48%, var(--border));
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px;
|
||||
color: var(--text-strong);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.empty-view {
|
||||
min-height: calc(100svh - 240px);
|
||||
display: grid;
|
||||
place-content: center;
|
||||
justify-items: start;
|
||||
gap: 18px;
|
||||
}
|
||||
|
||||
.empty-copy {
|
||||
margin: 16px 0 0;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.skeleton {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.skeleton::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
transparent,
|
||||
color-mix(in srgb, var(--text-muted) 10%, transparent),
|
||||
transparent
|
||||
);
|
||||
animation: skeleton-sheen 1.4s linear infinite;
|
||||
}
|
||||
|
||||
.skeleton-title {
|
||||
width: min(420px, 100%);
|
||||
height: 92px;
|
||||
}
|
||||
|
||||
.skeleton-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.skeleton-panel {
|
||||
min-height: 280px;
|
||||
}
|
||||
|
||||
@keyframes skeleton-sheen {
|
||||
from {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.app-main {
|
||||
width: min(100% - 24px, 720px);
|
||||
padding: 32px 0;
|
||||
}
|
||||
|
||||
.home-view,
|
||||
.dashboard-summary,
|
||||
.insight-grid,
|
||||
.champion-list,
|
||||
.skeleton-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.home-copy {
|
||||
min-height: auto;
|
||||
}
|
||||
|
||||
.summary-stat-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.app-header {
|
||||
min-height: auto;
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.header-status {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.home-copy,
|
||||
.analysis-form,
|
||||
.progress-panel,
|
||||
.chart-section,
|
||||
.champion-section,
|
||||
.insight-section,
|
||||
.similar-section,
|
||||
.dashboard-summary {
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.home-facts,
|
||||
.progress-meta,
|
||||
.summary-stat-grid,
|
||||
.metric-card-list {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.form-header,
|
||||
.section-heading {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.radar-frame {
|
||||
margin-inline: -8px;
|
||||
}
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { Suspense, lazy } from 'react';
|
||||
import { BrowserRouter, Link, Route, Routes } from 'react-router-dom';
|
||||
import './App.css';
|
||||
import { HomePage } from './pages/HomePage';
|
||||
import { NotFoundPage } from './pages/NotFoundPage';
|
||||
import { ProgressPage } from './pages/ProgressPage';
|
||||
|
||||
const DashboardPage = lazy(() =>
|
||||
import('./pages/DashboardPage').then((module) => ({
|
||||
default: module.DashboardPage,
|
||||
})),
|
||||
);
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<div className="app-shell">
|
||||
<header className="app-header">
|
||||
<Link className="brand" to="/" aria-label="persona-lenz 홈">
|
||||
<span className="brand-mark" aria-hidden="true">
|
||||
PL
|
||||
</span>
|
||||
<span className="brand-copy">
|
||||
<strong>persona-lenz</strong>
|
||||
<span>LoL 플레이스타일 분석</span>
|
||||
</span>
|
||||
</Link>
|
||||
<span className="header-status">Ranked Solo MVP</span>
|
||||
</header>
|
||||
|
||||
<main className="app-main">
|
||||
<Suspense fallback={<RouteFallback />}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/analysis/:jobId" element={<ProgressPage />} />
|
||||
<Route path="/players/:puuid" element={<DashboardPage />} />
|
||||
<Route path="*" element={<NotFoundPage />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
</main>
|
||||
|
||||
<footer className="riot-disclaimer">
|
||||
persona-lenz is not endorsed by Riot Games and does not reflect the
|
||||
views or opinions of Riot Games or anyone officially involved in
|
||||
producing or managing Riot Games properties. Riot Games and all
|
||||
associated properties are trademarks or registered trademarks of Riot
|
||||
Games, Inc.
|
||||
</footer>
|
||||
</div>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
function RouteFallback() {
|
||||
return (
|
||||
<section className="empty-view" aria-busy="true" aria-label="화면 로딩 중">
|
||||
<div className="skeleton skeleton-title" />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -1,110 +0,0 @@
|
||||
import type {
|
||||
AnalysisJobStatusDto,
|
||||
AnalysisRequestAcceptedDto,
|
||||
AnalysisRequestDto,
|
||||
PlayerAnalysisDto,
|
||||
SimilarPlayersDto,
|
||||
} from '@persona-lenz/shared';
|
||||
|
||||
export class ApiClientError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.name = 'ApiClientError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
const JSON_HEADERS = {
|
||||
'Content-Type': 'application/json',
|
||||
} as const;
|
||||
|
||||
async function fetchJson<T>(
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit,
|
||||
): Promise<T> {
|
||||
const response = await fetch(input, init);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new ApiClientError(await readErrorMessage(response), response.status);
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
async function readErrorMessage(response: Response): Promise<string> {
|
||||
const fallback = `요청 처리에 실패했습니다. (${response.status})`;
|
||||
const contentType = response.headers.get('content-type') ?? '';
|
||||
|
||||
if (!contentType.includes('application/json')) {
|
||||
const text = await response.text().catch(() => '');
|
||||
return text.trim() || fallback;
|
||||
}
|
||||
|
||||
const payload = await response.json().catch(() => undefined);
|
||||
|
||||
if (!isRecord(payload) || !('message' in payload)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const { message } = payload;
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
return message.map(String).join(', ');
|
||||
}
|
||||
|
||||
return typeof message === 'string' && message.trim() ? message : fallback;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null;
|
||||
}
|
||||
|
||||
export function getReadableErrorMessage(error: unknown): string {
|
||||
if (error instanceof ApiClientError) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return '알 수 없는 오류가 발생했습니다.';
|
||||
}
|
||||
|
||||
export async function requestAnalysis(
|
||||
payload: AnalysisRequestDto,
|
||||
): Promise<AnalysisRequestAcceptedDto> {
|
||||
return fetchJson<AnalysisRequestAcceptedDto>('/api/analysis/request', {
|
||||
method: 'POST',
|
||||
headers: JSON_HEADERS,
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getAnalysisJob(
|
||||
jobId: string,
|
||||
): Promise<AnalysisJobStatusDto> {
|
||||
return fetchJson<AnalysisJobStatusDto>(
|
||||
`/api/analysis/jobs/${encodeURIComponent(jobId)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getLatestPlayerAnalysis(
|
||||
puuid: string,
|
||||
): Promise<PlayerAnalysisDto> {
|
||||
return fetchJson<PlayerAnalysisDto>(
|
||||
`/api/players/${encodeURIComponent(puuid)}/analysis/latest`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSimilarPlayers(
|
||||
puuid: string,
|
||||
limit = 10,
|
||||
): Promise<SimilarPlayersDto> {
|
||||
const params = new URLSearchParams({ limit: String(limit) });
|
||||
return fetchJson<SimilarPlayersDto>(
|
||||
`/api/players/${encodeURIComponent(puuid)}/similar-players?${params}`,
|
||||
);
|
||||
}
|
||||
@@ -1,139 +0,0 @@
|
||||
const DATA_DRAGON_BASE_URL = 'https://ddragon.leagueoflegends.com';
|
||||
const CACHE_KEY = 'persona-lenz:data-dragon:champions:v1';
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
export interface ChampionSummary {
|
||||
id: number;
|
||||
imageUrl: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ChampionCatalog {
|
||||
champions: Record<number, ChampionSummary>;
|
||||
version: string;
|
||||
}
|
||||
|
||||
interface ChampionCatalogCache extends ChampionCatalog {
|
||||
cachedAt: number;
|
||||
}
|
||||
|
||||
interface DataDragonChampion {
|
||||
image: {
|
||||
full: string;
|
||||
};
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface DataDragonChampionResponse {
|
||||
data: Record<string, DataDragonChampion>;
|
||||
}
|
||||
|
||||
export async function loadChampionCatalog(): Promise<ChampionCatalog> {
|
||||
const cachedCatalog = readChampionCatalogCache();
|
||||
|
||||
if (cachedCatalog && Date.now() - cachedCatalog.cachedAt < CACHE_TTL_MS) {
|
||||
return cachedCatalog;
|
||||
}
|
||||
|
||||
try {
|
||||
const [latestVersion] = await fetchJson<string[]>(
|
||||
`${DATA_DRAGON_BASE_URL}/api/versions.json`,
|
||||
);
|
||||
|
||||
if (!latestVersion) {
|
||||
throw new Error('Data Dragon 버전 목록이 비어 있습니다.');
|
||||
}
|
||||
|
||||
const championResponse = await fetchJson<DataDragonChampionResponse>(
|
||||
`${DATA_DRAGON_BASE_URL}/cdn/${latestVersion}/data/ko_KR/champion.json`,
|
||||
);
|
||||
const champions = Object.values(championResponse.data).reduce<
|
||||
Record<number, ChampionSummary>
|
||||
>((catalog, champion) => {
|
||||
const championId = Number(champion.key);
|
||||
|
||||
if (Number.isFinite(championId)) {
|
||||
catalog[championId] = {
|
||||
id: championId,
|
||||
imageUrl: `${DATA_DRAGON_BASE_URL}/cdn/${latestVersion}/img/champion/${champion.image.full}`,
|
||||
name: champion.name,
|
||||
};
|
||||
}
|
||||
|
||||
return catalog;
|
||||
}, {});
|
||||
const catalog: ChampionCatalogCache = {
|
||||
cachedAt: Date.now(),
|
||||
champions,
|
||||
version: latestVersion,
|
||||
};
|
||||
|
||||
writeChampionCatalogCache(catalog);
|
||||
|
||||
return catalog;
|
||||
} catch (error) {
|
||||
if (cachedCatalog) {
|
||||
return cachedCatalog;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function readChampionCatalogCache(): ChampionCatalogCache | null {
|
||||
let rawCache: string | null;
|
||||
|
||||
try {
|
||||
rawCache = window.localStorage.getItem(CACHE_KEY);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!rawCache) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsedCache = JSON.parse(rawCache) as Partial<ChampionCatalogCache>;
|
||||
|
||||
if (
|
||||
typeof parsedCache.cachedAt === 'number' &&
|
||||
typeof parsedCache.version === 'string' &&
|
||||
parsedCache.champions &&
|
||||
typeof parsedCache.champions === 'object'
|
||||
) {
|
||||
return parsedCache as ChampionCatalogCache;
|
||||
}
|
||||
} catch {
|
||||
removeChampionCatalogCache();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function writeChampionCatalogCache(catalog: ChampionCatalogCache): void {
|
||||
try {
|
||||
window.localStorage.setItem(CACHE_KEY, JSON.stringify(catalog));
|
||||
} catch {
|
||||
// Champion metadata remains usable even when browser storage is restricted.
|
||||
}
|
||||
}
|
||||
|
||||
function removeChampionCatalogCache(): void {
|
||||
try {
|
||||
window.localStorage.removeItem(CACHE_KEY);
|
||||
} catch {
|
||||
// Ignore storage failures.
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string): Promise<T> {
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Data Dragon 요청에 실패했습니다. (${response.status})`);
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/* Scaffolded with StyleSeed · github.com/bitjaru/styleseed — safe to remove */
|
||||
import * as React from 'react'
|
||||
import { Routes, Route } from 'react-router-dom'
|
||||
import { HomePage } from '../pages/home'
|
||||
import { AnalysisProgressPage } from '../pages/analysis-progress'
|
||||
|
||||
// recharts를 포함한 대시보드는 무거우므로 분리 로딩 — 홈/진행 화면 첫 로드를 가볍게 유지
|
||||
const PlayerDashboardPage = React.lazy(() =>
|
||||
import('../pages/player-dashboard').then((module) => ({ default: module.PlayerDashboardPage })),
|
||||
)
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/analysis/:jobId" element={<AnalysisProgressPage />} />
|
||||
<Route
|
||||
path="/players/:puuid"
|
||||
element={
|
||||
<React.Suspense fallback={<div className="min-h-dvh bg-surface-page" />}>
|
||||
<PlayerDashboardPage />
|
||||
</React.Suspense>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ChampionPoolEntryDto } from '@persona-lenz/shared'
|
||||
import type { ChampionIndex } from '../../lib/ddragon'
|
||||
import { championImageUrl } from '../../lib/ddragon'
|
||||
|
||||
interface ChampionPoolCardProps {
|
||||
championPool: ChampionPoolEntryDto[]
|
||||
champions: ChampionIndex | null
|
||||
}
|
||||
|
||||
/** 분석 표본에 포함된 챔피언 풀 — 판수 내림차순 상위 5개 */
|
||||
export function ChampionPoolCard({ championPool, champions }: ChampionPoolCardProps) {
|
||||
const entries = championPool.slice(0, 5)
|
||||
|
||||
return (
|
||||
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||
<h2 className="text-[18px] font-bold text-text-primary">챔피언 풀</h2>
|
||||
<p className="mt-1 text-[13px] text-text-tertiary">이번 분석 표본에서 많이 플레이한 순이에요.</p>
|
||||
<ul className="mt-4 divide-y divide-border">
|
||||
{entries.map((entry) => {
|
||||
const champion = champions?.byId.get(entry.championId)
|
||||
const winRate = entry.games > 0 ? Math.round((entry.wins / entry.games) * 100) : 0
|
||||
return (
|
||||
<li key={entry.championId} className="flex items-center gap-4 py-3">
|
||||
{champion && champions ? (
|
||||
<img
|
||||
src={championImageUrl(champions.version, champion.slug)}
|
||||
alt=""
|
||||
className="size-10 rounded-lg"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<span aria-hidden className="size-10 rounded-lg bg-surface-muted" />
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[15px] font-bold text-text-primary">
|
||||
{champion?.name ?? `챔피언 #${entry.championId}`}
|
||||
</p>
|
||||
<p className="text-[13px] tabular-nums text-text-tertiary">
|
||||
{entry.games}전 {entry.wins}승
|
||||
</p>
|
||||
</div>
|
||||
<span className="text-[17px] font-bold tabular-nums text-text-primary">
|
||||
{winRate}
|
||||
<span className="text-[11px] font-medium text-text-tertiary">%</span>
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { MetricId } from '@persona-lenz/shared'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'
|
||||
import { METRIC_BY_ID, METRIC_CATEGORIES, displayScore } from '../../lib/metrics'
|
||||
|
||||
interface MetricDetailTabsProps {
|
||||
playstyle: Partial<Record<MetricId, number>>
|
||||
}
|
||||
|
||||
/** 39개 전체 지표를 6개 카테고리 탭으로 드릴다운. 막대는 상태가 아니라 크기이므로 중립색 */
|
||||
export function MetricDetailTabs({ playstyle }: MetricDetailTabsProps) {
|
||||
const categories = METRIC_CATEGORIES.map((category) => ({
|
||||
...category,
|
||||
metrics: category.metricIds
|
||||
.filter((metricId) => playstyle[metricId] != null)
|
||||
.map((metricId) => ({
|
||||
metric: METRIC_BY_ID.get(metricId),
|
||||
metricId,
|
||||
score: displayScore(metricId, playstyle[metricId]!),
|
||||
})),
|
||||
})).filter((category) => category.metrics.length > 0)
|
||||
|
||||
if (categories.length === 0) return null
|
||||
|
||||
return (
|
||||
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||
<h2 className="text-[18px] font-bold text-text-primary">전체 지표</h2>
|
||||
<p className="mt-1 text-[13px] text-text-tertiary">
|
||||
같은 포지션 기준으로 정규화한 0~100 점수예요. 낮을수록 좋은 지표는 반전해서 표시합니다.
|
||||
</p>
|
||||
<Tabs defaultValue={categories[0].id} className="mt-4">
|
||||
<TabsList className="h-auto w-full flex-wrap justify-start">
|
||||
{categories.map((category) => (
|
||||
<TabsTrigger key={category.id} value={category.id}>
|
||||
{category.label}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
{categories.map((category) => (
|
||||
<TabsContent key={category.id} value={category.id}>
|
||||
<ul className="divide-y divide-border">
|
||||
{category.metrics.map(({ metric, metricId, score }) => (
|
||||
<li key={metricId} className="flex items-center gap-6 py-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[15px] font-medium text-text-primary">{metric?.label ?? metricId}</p>
|
||||
<p className="mt-0.5 text-[13px] leading-relaxed text-text-tertiary">{metric?.description}</p>
|
||||
</div>
|
||||
<div className="flex w-32 shrink-0 items-center gap-3 sm:w-44">
|
||||
<div
|
||||
aria-hidden
|
||||
className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-muted"
|
||||
>
|
||||
<div className="h-full rounded-full bg-primary/40" style={{ width: `${score}%` }} />
|
||||
</div>
|
||||
<span className="w-7 text-right text-[15px] font-bold tabular-nums text-text-primary">
|
||||
{score}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</TabsContent>
|
||||
))}
|
||||
</Tabs>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { TrendingDown, TrendingUp } from 'lucide-react'
|
||||
import type { MetricValueDto } from '@persona-lenz/shared'
|
||||
import { METRIC_BY_ID, displayScore } from '../../lib/metrics'
|
||||
|
||||
interface MetricHighlightsProps {
|
||||
strengths: MetricValueDto[]
|
||||
weaknesses: MetricValueDto[]
|
||||
}
|
||||
|
||||
function HighlightList({ items, tone }: { items: MetricValueDto[]; tone: 'strength' | 'weakness' }) {
|
||||
return (
|
||||
<ol className="mt-5 space-y-5">
|
||||
{items.map(({ metricId, value }, index) => {
|
||||
const metric = METRIC_BY_ID.get(metricId)
|
||||
return (
|
||||
<li key={metricId} className="flex items-start gap-4">
|
||||
<span className="w-5 shrink-0 pt-0.5 text-[15px] font-bold tabular-nums text-text-tertiary">
|
||||
{index + 1}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-[15px] font-bold text-text-primary">{metric?.label ?? metricId}</p>
|
||||
<p className="mt-1 text-[13px] leading-relaxed text-text-tertiary">{metric?.description}</p>
|
||||
</div>
|
||||
<span
|
||||
className={`shrink-0 text-[17px] font-bold tabular-nums ${
|
||||
tone === 'strength' ? 'text-brand' : 'text-warning'
|
||||
}`}
|
||||
>
|
||||
{displayScore(metricId, value)}
|
||||
</span>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
)
|
||||
}
|
||||
|
||||
/** 강점/약점 Top 3 — direction 반영 점수(0~100)와 지표 설명을 함께 보여준다 */
|
||||
export function MetricHighlights({ strengths, weaknesses }: MetricHighlightsProps) {
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||
<h2 className="flex items-center gap-2 text-[18px] font-bold text-text-primary">
|
||||
<TrendingUp aria-hidden className="size-5 text-brand" />
|
||||
이런 플레이가 강해요
|
||||
</h2>
|
||||
<HighlightList items={strengths.slice(0, 3)} tone="strength" />
|
||||
</section>
|
||||
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||
<h2 className="flex items-center gap-2 text-[18px] font-bold text-text-primary">
|
||||
<TrendingDown aria-hidden className="size-5 text-warning" />
|
||||
여기를 보완하면 좋아요
|
||||
</h2>
|
||||
<HighlightList items={weaknesses.slice(0, 3)} tone="weakness" />
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { PolarAngleAxis, PolarGrid, PolarRadiusAxis, Radar, RadarChart, ResponsiveContainer } from 'recharts'
|
||||
import type { CategoryScore } from '../../lib/metrics'
|
||||
|
||||
interface PlaystyleRadarProps {
|
||||
scores: CategoryScore[]
|
||||
}
|
||||
|
||||
/** 6개 카테고리 집계 점수를 보여주는 플레이스타일 레이더. 대시보드의 focal 요소 */
|
||||
export function PlaystyleRadar({ scores }: PlaystyleRadarProps) {
|
||||
const data = scores.map(({ category, score }) => ({
|
||||
label: category.label,
|
||||
score: score ?? 0,
|
||||
}))
|
||||
|
||||
return (
|
||||
<div className="h-[300px] w-full" role="img" aria-label="플레이스타일 카테고리 레이더 차트">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<RadarChart data={data} outerRadius="72%" margin={{ top: 12, right: 24, bottom: 12, left: 24 }}>
|
||||
<PolarGrid stroke="var(--border)" />
|
||||
<PolarAngleAxis
|
||||
dataKey="label"
|
||||
tick={{ fill: 'var(--text-secondary)', fontSize: 13, fontWeight: 500 }}
|
||||
/>
|
||||
<PolarRadiusAxis domain={[0, 100]} tick={false} axisLine={false} />
|
||||
<Radar
|
||||
dataKey="score"
|
||||
stroke="var(--brand)"
|
||||
strokeWidth={2}
|
||||
fill="var(--brand)"
|
||||
fillOpacity={0.16}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
</RadarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Users } from 'lucide-react'
|
||||
import type { SimilarPlayerDto } from '@persona-lenz/shared'
|
||||
import type { ChampionIndex } from '../../lib/ddragon'
|
||||
import { championImageUrl } from '../../lib/ddragon'
|
||||
import { METRIC_BY_ID, ROLE_LABELS, formatTier } from '../../lib/metrics'
|
||||
|
||||
interface SimilarPlayersSectionProps {
|
||||
players: SimilarPlayerDto[] | null
|
||||
champions: ChampionIndex | null
|
||||
}
|
||||
|
||||
function LeadChips({ player }: { player: SimilarPlayerDto }) {
|
||||
if (player.strongerMetrics.length === 0) return null
|
||||
return (
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
<span className="text-[13px] text-text-tertiary">이 플레이어가 앞서는 지표</span>
|
||||
{player.strongerMetrics.slice(0, 3).map((lead) => (
|
||||
<span
|
||||
key={lead.metricId}
|
||||
className="rounded-md bg-surface-muted px-2 py-1 text-[13px] font-medium text-text-secondary"
|
||||
>
|
||||
{METRIC_BY_ID.get(lead.metricId)?.label ?? lead.metricId} +{Math.round(lead.lead * 100)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** 나와 비슷한 플레이스타일의 상위 티어 유저 비교 카드 목록 */
|
||||
export function SimilarPlayersSection({ players, champions }: SimilarPlayersSectionProps) {
|
||||
return (
|
||||
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||
<h2 className="text-[18px] font-bold text-text-primary">나와 비슷한 상위 티어 플레이어</h2>
|
||||
<p className="mt-1 text-[13px] text-text-tertiary">
|
||||
플레이스타일 벡터가 가까운 유저 중 더 높은 티어를 우선으로 보여드려요.
|
||||
</p>
|
||||
|
||||
{players == null || players.length === 0 ? (
|
||||
<div className="mt-6 flex flex-col items-center rounded-xl bg-surface-subtle px-6 py-10 text-center">
|
||||
<Users aria-hidden className="size-8 text-text-disabled" />
|
||||
<p className="mt-3 text-[15px] font-medium text-text-primary">아직 비교 결과를 준비 중이에요</p>
|
||||
<p className="mt-1 text-[14px] text-text-tertiary">
|
||||
비교 풀이 채워지면 자동으로 나타나요. 다음 분석 때 다시 확인해 주세요.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="mt-5 space-y-4">
|
||||
{players.map((player) => {
|
||||
const name = player.riotId ? `${player.riotId.gameName}#${player.riotId.tagLine}` : player.displayId
|
||||
const tier = formatTier(player.tier, player.division)
|
||||
return (
|
||||
<li key={player.displayId} className="rounded-xl bg-surface-subtle p-5">
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||
<p className="text-[15px] font-bold text-text-primary">{name}</p>
|
||||
{tier && (
|
||||
<span className="rounded-md bg-surface-muted px-2 py-0.5 text-[13px] font-medium text-text-secondary">
|
||||
{tier}
|
||||
{player.leaguePoints != null ? ` · ${player.leaguePoints}LP` : ''}
|
||||
</span>
|
||||
)}
|
||||
{player.tierComparison === 'higher' && (
|
||||
<span className="rounded-md bg-brand-tint px-2 py-0.5 text-[13px] font-bold text-brand">
|
||||
상위 티어
|
||||
</span>
|
||||
)}
|
||||
<span className="ms-auto text-[15px] font-bold tabular-nums text-text-primary">
|
||||
유사도 {Math.round(player.similarityScore * 100)}
|
||||
<span className="text-[11px] font-medium text-text-tertiary">%</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-3 flex items-center gap-3">
|
||||
<span className="text-[13px] text-text-tertiary">{ROLE_LABELS[player.mainRole]}</span>
|
||||
<span aria-hidden className="size-0.5 rounded-full bg-text-disabled" />
|
||||
<span className="text-[13px] text-text-tertiary">{player.sampleGameCount}게임 표본</span>
|
||||
{champions && player.mainChampions.length > 0 && (
|
||||
<div className="ms-2 flex items-center gap-1.5">
|
||||
{player.mainChampions.slice(0, 3).map((entry) => {
|
||||
const champion = champions.byId.get(entry.championId)
|
||||
if (!champion) return null
|
||||
return (
|
||||
<img
|
||||
key={entry.championId}
|
||||
src={championImageUrl(champions.version, champion.slug)}
|
||||
alt={champion.name}
|
||||
title={champion.name}
|
||||
className="size-7 rounded-md"
|
||||
loading="lazy"
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<LeadChips player={player} />
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
import type { LucideIcon } from "lucide-react"
|
||||
|
||||
interface NavItem {
|
||||
name: string
|
||||
icon: LucideIcon
|
||||
href?: string
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
interface BottomNavProps extends React.ComponentProps<"nav"> {
|
||||
items: NavItem[]
|
||||
activeIndex?: number
|
||||
maxWidth?: string
|
||||
}
|
||||
|
||||
function BottomNav({
|
||||
items,
|
||||
activeIndex = 0,
|
||||
maxWidth = "430px",
|
||||
className,
|
||||
...props
|
||||
}: BottomNavProps) {
|
||||
return (
|
||||
<nav
|
||||
data-slot="bottom-nav"
|
||||
className={cn(
|
||||
"fixed bottom-0 left-0 right-0 bg-card border-t border-surface-muted pb-safe",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div
|
||||
className="mx-auto flex items-center justify-around px-6 py-3"
|
||||
style={{ maxWidth }}
|
||||
>
|
||||
{items.map((item, index) => {
|
||||
const Icon = item.icon
|
||||
const isActive = index === activeIndex
|
||||
return (
|
||||
<button
|
||||
key={item.name}
|
||||
onClick={item.onClick}
|
||||
className={cn(
|
||||
"flex flex-col items-center gap-1 min-w-11 min-h-11 justify-center",
|
||||
"transition-colors duration-[var(--duration-fast)]",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-lg",
|
||||
isActive ? "text-brand" : "text-text-disabled",
|
||||
)}
|
||||
>
|
||||
<Icon className="size-5" strokeWidth={2} />
|
||||
<span className="text-[10px] font-semibold">{item.name}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
|
||||
export { BottomNav }
|
||||
export type { BottomNavProps, NavItem }
|
||||
@@ -0,0 +1,76 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
import type { LucideIcon } from "lucide-react"
|
||||
|
||||
interface BriefingItem {
|
||||
icon: LucideIcon
|
||||
badge: string
|
||||
badgeColor: string
|
||||
title: string
|
||||
description: string
|
||||
}
|
||||
|
||||
interface BriefingCarouselProps extends React.ComponentProps<"div"> {
|
||||
title?: string
|
||||
items: BriefingItem[]
|
||||
cardWidth?: string
|
||||
}
|
||||
|
||||
function BriefingCarousel({
|
||||
title,
|
||||
items,
|
||||
cardWidth = "280px",
|
||||
className,
|
||||
...props
|
||||
}: BriefingCarouselProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="briefing-carousel"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
>
|
||||
{title && (
|
||||
<h3 className="text-text-primary font-bold text-[18px] leading-snug mb-4">
|
||||
{title}
|
||||
</h3>
|
||||
)}
|
||||
<div className="flex gap-3 overflow-x-auto pb-2 scrollbar-hide">
|
||||
{items.map((item, index) => {
|
||||
const IconComponent = item.icon
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className="flex-shrink-0 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]"
|
||||
style={{ width: cardWidth }}
|
||||
>
|
||||
<div className="mb-4">
|
||||
<div className="flex items-center gap-1.5 mb-3">
|
||||
<IconComponent
|
||||
className="size-4"
|
||||
style={{ color: item.badgeColor }}
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
<span
|
||||
className="text-[12px] font-bold uppercase tracking-[0.05em]"
|
||||
style={{ color: item.badgeColor }}
|
||||
>
|
||||
{item.badge}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-text-primary text-[15px] font-bold mb-2 leading-tight">
|
||||
{item.title}
|
||||
</p>
|
||||
<p className="text-text-tertiary text-[13px]">
|
||||
{item.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { BriefingCarousel }
|
||||
export type { BriefingCarouselProps, BriefingItem }
|
||||
@@ -0,0 +1,101 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface ChartStat {
|
||||
label: string
|
||||
value: string | number
|
||||
unit?: string
|
||||
}
|
||||
|
||||
interface ChartCardProps extends React.ComponentProps<"div"> {
|
||||
title?: string
|
||||
headerLeft?: React.ReactNode
|
||||
periods?: string[]
|
||||
activePeriod?: string
|
||||
onPeriodChange?: (period: string) => void
|
||||
stats?: ChartStat[]
|
||||
statsColumns?: number
|
||||
}
|
||||
|
||||
function ChartCard({
|
||||
title,
|
||||
headerLeft,
|
||||
periods,
|
||||
activePeriod,
|
||||
onPeriodChange,
|
||||
stats,
|
||||
statsColumns = 3,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: ChartCardProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="chart-card"
|
||||
className={cn(
|
||||
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<div>
|
||||
{title && (
|
||||
<h3 className="text-text-primary font-bold text-[18px] leading-snug">
|
||||
{title}
|
||||
</h3>
|
||||
)}
|
||||
{headerLeft}
|
||||
</div>
|
||||
|
||||
{periods && (
|
||||
<div className="flex gap-1 bg-surface-muted p-1 rounded-full">
|
||||
{periods.map((period) => (
|
||||
<button
|
||||
key={period}
|
||||
onClick={() => onPeriodChange?.(period)}
|
||||
className={cn(
|
||||
"px-4 py-1.5 text-[11px] font-semibold rounded-full transition-all",
|
||||
activePeriod === period
|
||||
? "bg-brand text-white shadow-sm"
|
||||
: "text-text-tertiary",
|
||||
)}
|
||||
>
|
||||
{period}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="h-40 -mx-2 mb-6">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{stats && stats.length > 0 && (
|
||||
<div
|
||||
className="gap-3 pt-5 border-t border-surface-muted"
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: `repeat(${statsColumns}, 1fr)`,
|
||||
}}
|
||||
>
|
||||
{stats.map((stat) => (
|
||||
<div key={stat.label} className="text-center">
|
||||
<p className="text-[11px] text-text-secondary mb-2 font-medium uppercase">
|
||||
{stat.label}
|
||||
</p>
|
||||
<p className="text-text-primary font-bold text-[18px] leading-none whitespace-nowrap">
|
||||
{stat.value}
|
||||
{stat.unit && <span className="text-[10px] ms-0.5">{stat.unit}</span>}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { ChartCard }
|
||||
export type { ChartCardProps, ChartStat }
|
||||
@@ -0,0 +1,140 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface DonutItem {
|
||||
name: string
|
||||
value: number
|
||||
stock?: string | number
|
||||
unit?: string
|
||||
}
|
||||
|
||||
interface BottomStat {
|
||||
label: string
|
||||
value: string | number
|
||||
subLabel?: string
|
||||
}
|
||||
|
||||
interface DonutChartCardProps extends React.ComponentProps<"div"> {
|
||||
title: string
|
||||
centerValue?: string | number
|
||||
centerUnit?: string
|
||||
centerLabel?: string
|
||||
items: DonutItem[]
|
||||
selectedItem?: string | null
|
||||
onItemSelect?: (name: string | null) => void
|
||||
bottomStats?: BottomStat[]
|
||||
bottomColumns?: number
|
||||
chartElement: React.ReactNode
|
||||
}
|
||||
|
||||
function DonutChartCard({
|
||||
title,
|
||||
centerValue,
|
||||
centerUnit,
|
||||
centerLabel,
|
||||
items,
|
||||
selectedItem,
|
||||
onItemSelect,
|
||||
bottomStats,
|
||||
bottomColumns = 4,
|
||||
chartElement,
|
||||
className,
|
||||
...props
|
||||
}: DonutChartCardProps) {
|
||||
const grayColors = ["#D4D4D4", "#A8A8A8", "#8B8B8B", "#6B6B6B"]
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="donut-chart-card"
|
||||
className={cn(
|
||||
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<h3 className="text-text-primary font-bold text-[18px] leading-snug mb-4">
|
||||
{title}
|
||||
</h3>
|
||||
|
||||
<div className="flex items-center gap-8">
|
||||
<div className="relative size-32 flex-shrink-0">
|
||||
{chartElement}
|
||||
{(centerValue !== undefined || centerLabel) && (
|
||||
<div className="absolute inset-0 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
{centerValue !== undefined && (
|
||||
<p className="text-text-primary text-[24px] font-bold leading-none whitespace-nowrap">
|
||||
{centerValue}
|
||||
{centerUnit && <span className="text-[12px] ms-0.5">{centerUnit}</span>}
|
||||
</p>
|
||||
)}
|
||||
{centerLabel && (
|
||||
<p className="text-text-tertiary text-[10px] mt-1 font-medium uppercase">
|
||||
{centerLabel}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 space-y-3.5">
|
||||
{items.map((item, index) => (
|
||||
<div
|
||||
key={item.name}
|
||||
className="flex items-center justify-between cursor-pointer transition-all duration-300"
|
||||
onClick={() => onItemSelect?.(selectedItem === item.name ? null : item.name)}
|
||||
style={{
|
||||
opacity: selectedItem === null || selectedItem === undefined || selectedItem === item.name ? 1 : 0.3,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<div
|
||||
className="size-3 rounded-full transition-all duration-300"
|
||||
style={{
|
||||
backgroundColor: selectedItem === item.name ? "var(--brand)" : grayColors[index % grayColors.length],
|
||||
boxShadow: selectedItem === item.name ? "0 0 0 2px color-mix(in srgb, var(--brand) 25%, transparent)" : "none",
|
||||
}}
|
||||
/>
|
||||
<span className="text-text-primary text-[13px] font-semibold">{item.name}</span>
|
||||
</div>
|
||||
{item.stock !== undefined && (
|
||||
<span className="text-text-primary text-[15px] font-bold whitespace-nowrap">
|
||||
{item.stock}
|
||||
{item.unit && <span className="text-[10px] ms-0.5">{item.unit}</span>}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{bottomStats && bottomStats.length > 0 && (
|
||||
<div
|
||||
className="gap-3 mt-6 pt-6 border-t border-surface-muted"
|
||||
style={{
|
||||
display: "grid",
|
||||
gridTemplateColumns: `repeat(${bottomColumns}, 1fr)`,
|
||||
}}
|
||||
>
|
||||
{bottomStats.map((stat) => (
|
||||
<div key={stat.label} className="text-center">
|
||||
<p className="text-[11px] text-text-secondary mb-1.5 font-medium uppercase">
|
||||
{stat.label}
|
||||
</p>
|
||||
<p className="text-text-primary font-bold text-[20px] leading-none">
|
||||
{stat.value}
|
||||
</p>
|
||||
{stat.subLabel && (
|
||||
<p className="text-[11px] text-text-secondary mt-0.5">{stat.subLabel}</p>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { DonutChartCard }
|
||||
export type { DonutChartCardProps, DonutItem, BottomStat }
|
||||
@@ -0,0 +1,48 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
import type { LucideIcon } from "lucide-react"
|
||||
|
||||
interface EmptyStateProps extends React.ComponentProps<"div"> {
|
||||
icon?: LucideIcon
|
||||
title: string
|
||||
description?: string
|
||||
action?: React.ReactNode
|
||||
}
|
||||
|
||||
function EmptyState({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
className,
|
||||
...props
|
||||
}: EmptyStateProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-state"
|
||||
className={cn(
|
||||
"flex flex-col items-center justify-center py-12 px-6 text-center",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{Icon && (
|
||||
<div className="size-8 rounded-xl bg-surface-muted flex items-center justify-center mb-3">
|
||||
<Icon className="size-4 text-text-tertiary" strokeWidth={1.5} />
|
||||
</div>
|
||||
)}
|
||||
<h3 className="text-[16px] font-bold text-text-primary tracking-[-0.01em] mb-1.5">
|
||||
{title}
|
||||
</h3>
|
||||
{description && (
|
||||
<p className="text-[14px] leading-normal text-text-secondary mb-6 max-w-[280px]">
|
||||
{description}
|
||||
</p>
|
||||
)}
|
||||
{action}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { EmptyState }
|
||||
export type { EmptyStateProps }
|
||||
@@ -0,0 +1,96 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
import { TrendingUp, TrendingDown, type LucideIcon } from "lucide-react"
|
||||
|
||||
interface HeroCardProps extends React.ComponentProps<"div"> {
|
||||
icon: LucideIcon
|
||||
label: string
|
||||
value: string | number
|
||||
unit?: string
|
||||
trend?: {
|
||||
value: string
|
||||
direction: "up" | "down"
|
||||
label?: string
|
||||
}
|
||||
backgroundElement?: React.ReactNode
|
||||
watermarkIcon?: LucideIcon
|
||||
}
|
||||
|
||||
function HeroCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
unit,
|
||||
trend,
|
||||
backgroundElement,
|
||||
watermarkIcon: WatermarkIcon,
|
||||
className,
|
||||
...props
|
||||
}: HeroCardProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="hero-card"
|
||||
className={cn(
|
||||
"mx-6 rounded-2xl bg-card p-8 shadow-[var(--shadow-card)] relative overflow-hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{backgroundElement && (
|
||||
<div className="absolute inset-0 opacity-[0.15]">
|
||||
{backgroundElement}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{WatermarkIcon && (
|
||||
<div className="absolute right-6 top-1/2 -translate-y-1/2 opacity-[0.06]">
|
||||
<WatermarkIcon className="size-32 text-brand" strokeWidth={1.5} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative z-10">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<div className="size-8 rounded-xl bg-brand/10 flex items-center justify-center">
|
||||
<Icon className="size-[18px] text-brand" strokeWidth={2} />
|
||||
</div>
|
||||
<p className="text-[12px] text-text-secondary font-medium uppercase tracking-[0.05em]">
|
||||
{label}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className="text-text-primary text-[48px] font-bold leading-none tracking-[-0.02em] mb-4 whitespace-nowrap">
|
||||
{value}
|
||||
{unit && <span className="text-[24px] ms-0.5 tracking-normal">{unit}</span>}
|
||||
</p>
|
||||
|
||||
{trend && (
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<span
|
||||
className={cn(
|
||||
"text-[15px] font-bold",
|
||||
trend.direction === "up" ? "text-success" : "text-destructive",
|
||||
)}
|
||||
>
|
||||
{trend.value}
|
||||
</span>
|
||||
{trend.direction === "up" ? (
|
||||
<TrendingUp className="size-4 text-success" strokeWidth={2.5} />
|
||||
) : (
|
||||
<TrendingDown className="size-4 text-destructive" strokeWidth={2.5} />
|
||||
)}
|
||||
</div>
|
||||
{trend.label && (
|
||||
<span className="text-[13px] text-text-tertiary font-medium">
|
||||
{trend.label}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { HeroCard }
|
||||
export type { HeroCardProps }
|
||||
@@ -0,0 +1,69 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
import type { LucideIcon } from "lucide-react"
|
||||
|
||||
interface InsightCardProps extends React.ComponentProps<"div"> {
|
||||
icon?: LucideIcon
|
||||
title: string
|
||||
description: string
|
||||
tags?: { label: string; icon?: LucideIcon }[]
|
||||
action?: React.ReactNode
|
||||
variant?: "default" | "highlighted"
|
||||
}
|
||||
|
||||
function InsightCard({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
tags,
|
||||
action,
|
||||
variant = "default",
|
||||
className,
|
||||
...props
|
||||
}: InsightCardProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="insight-card"
|
||||
className={cn(
|
||||
"mx-6 rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||
variant === "highlighted"
|
||||
? "bg-brand-tint border border-brand/20"
|
||||
: "bg-card",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{Icon && (
|
||||
<div className="size-8 rounded-xl bg-brand/10 flex items-center justify-center mb-3">
|
||||
<Icon className="size-[18px] text-brand" strokeWidth={2} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-text-primary font-bold text-[15px] leading-tight mb-2">
|
||||
{title}
|
||||
</p>
|
||||
<p className="text-text-tertiary text-[13px] leading-normal mb-4">
|
||||
{description}
|
||||
</p>
|
||||
|
||||
{tags && tags.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 mb-4">
|
||||
{tags.map((tag, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="inline-flex items-center gap-1 px-2.5 py-1 bg-surface-muted rounded-full text-[11px] font-medium text-text-secondary"
|
||||
>
|
||||
{tag.icon && <tag.icon className="size-3" />}
|
||||
{tag.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{action}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { InsightCard }
|
||||
export type { InsightCardProps }
|
||||
@@ -0,0 +1,64 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface ListItemProps extends React.ComponentProps<"div"> {
|
||||
leading?: React.ReactNode
|
||||
title: string
|
||||
subtitle?: React.ReactNode
|
||||
trailing?: React.ReactNode
|
||||
status?: {
|
||||
label: string
|
||||
color: string
|
||||
}
|
||||
}
|
||||
|
||||
function ListItem({
|
||||
leading,
|
||||
title,
|
||||
subtitle,
|
||||
trailing,
|
||||
status,
|
||||
className,
|
||||
...props
|
||||
}: ListItemProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="list-item"
|
||||
className={cn(
|
||||
"flex items-center justify-between p-5 rounded-xl bg-surface-subtle",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex items-center gap-3.5">
|
||||
{leading}
|
||||
<div>
|
||||
<p className="text-text-primary font-bold text-[14px] leading-snug mb-1.5">
|
||||
{title}
|
||||
</p>
|
||||
{status && (
|
||||
<div className="inline-flex items-center">
|
||||
<span
|
||||
className="size-1.5 rounded-full me-1.5"
|
||||
style={{ backgroundColor: status.color }}
|
||||
/>
|
||||
<span
|
||||
className="text-[11px] font-bold"
|
||||
style={{ color: status.color }}
|
||||
>
|
||||
{status.label}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{subtitle && !status && (
|
||||
<p className="text-[12px] text-text-secondary">{subtitle}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{trailing && <div className="flex-shrink-0">{trailing}</div>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { ListItem }
|
||||
export type { ListItemProps }
|
||||
@@ -0,0 +1,67 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface NewsCardProps extends React.ComponentProps<"div"> {
|
||||
title: string
|
||||
summary?: string
|
||||
source?: string
|
||||
timestamp?: string
|
||||
trend?: "up" | "down" | "neutral"
|
||||
onClick?: () => void
|
||||
}
|
||||
|
||||
function NewsCard({
|
||||
title,
|
||||
summary,
|
||||
source,
|
||||
timestamp,
|
||||
trend,
|
||||
onClick,
|
||||
className,
|
||||
...props
|
||||
}: NewsCardProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="news-card"
|
||||
className={cn(
|
||||
"bg-card rounded-2xl p-5 shadow-[var(--shadow-card)]",
|
||||
onClick && "cursor-pointer active:bg-surface-subtle transition-colors duration-150",
|
||||
className,
|
||||
)}
|
||||
onClick={onClick}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-text-primary font-bold text-[14px] leading-snug line-clamp-2 mb-1.5">
|
||||
{title}
|
||||
</p>
|
||||
{summary && (
|
||||
<p className="text-text-tertiary text-[13px] leading-normal line-clamp-2 mb-2">
|
||||
{summary}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-2 text-[11px] text-text-disabled">
|
||||
{source && <span>{source}</span>}
|
||||
{source && timestamp && <span>·</span>}
|
||||
{timestamp && <span>{timestamp}</span>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{trend && trend !== "neutral" && (
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 text-[12px] font-bold mt-0.5",
|
||||
trend === "up" ? "text-destructive" : "text-info",
|
||||
)}
|
||||
>
|
||||
{trend === "up" ? "▲" : "▼"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { NewsCard }
|
||||
export type { NewsCardProps }
|
||||
@@ -0,0 +1,42 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface PageShellProps extends React.ComponentProps<"div"> {
|
||||
maxWidth?: string
|
||||
}
|
||||
|
||||
function PageShell({
|
||||
maxWidth = "430px",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: PageShellProps) {
|
||||
return (
|
||||
<div className="min-h-screen bg-surface-page" {...props}>
|
||||
<div
|
||||
data-slot="page-shell"
|
||||
className={cn("mx-auto bg-surface-page min-h-screen relative", className)}
|
||||
style={{ maxWidth }}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
type PageContentProps = React.ComponentProps<"main">
|
||||
|
||||
function PageContent({ className, children, ...props }: PageContentProps) {
|
||||
return (
|
||||
<main
|
||||
data-slot="page-content"
|
||||
className={cn("pb-24 space-y-6", className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
export { PageShell, PageContent }
|
||||
export type { PageShellProps, PageContentProps }
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
/* === Linear Progress Bar === */
|
||||
|
||||
interface ProgressBarProps extends React.ComponentProps<"div"> {
|
||||
value: number
|
||||
max?: number
|
||||
height?: string
|
||||
label?: string
|
||||
}
|
||||
|
||||
function ProgressBar({
|
||||
value,
|
||||
max = 100,
|
||||
height = "h-4",
|
||||
label,
|
||||
className,
|
||||
...props
|
||||
}: ProgressBarProps) {
|
||||
const percent = Math.min(100, Math.max(0, (value / max) * 100))
|
||||
return (
|
||||
<div data-slot="progress-bar" className={cn("", className)} {...props}>
|
||||
<div className={cn("bg-surface-muted rounded-full overflow-hidden", height)}>
|
||||
<div
|
||||
className={cn("bg-brand h-full rounded-full transition-all duration-300")}
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
{label && (
|
||||
<p className="text-[11px] text-text-primary mt-2 font-bold">{label}</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* === Discrete Bar Segments (게이지) === */
|
||||
|
||||
interface DiscreteBarProps extends React.ComponentProps<"div"> {
|
||||
total: number
|
||||
filled: number
|
||||
height?: string
|
||||
}
|
||||
|
||||
function DiscreteBar({
|
||||
total,
|
||||
filled,
|
||||
height = "h-6",
|
||||
className,
|
||||
...props
|
||||
}: DiscreteBarProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="discrete-bar"
|
||||
className={cn("flex gap-1", className)}
|
||||
{...props}
|
||||
>
|
||||
{[...Array(total)].map((_, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className={cn(
|
||||
"flex-1 rounded",
|
||||
height,
|
||||
i < filled ? "bg-brand" : "bg-surface-muted",
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/* === Progress Bar with Label (오늘 방문 스타일) === */
|
||||
|
||||
interface ProgressBarWithLabelProps extends React.ComponentProps<"div"> {
|
||||
value: number
|
||||
max?: number
|
||||
label: string
|
||||
}
|
||||
|
||||
function ProgressBarWithLabel({
|
||||
value,
|
||||
max = 100,
|
||||
label,
|
||||
className,
|
||||
...props
|
||||
}: ProgressBarWithLabelProps) {
|
||||
const percent = Math.min(100, Math.max(0, (value / max) * 100))
|
||||
return (
|
||||
<div
|
||||
data-slot="progress-bar-with-label"
|
||||
className={cn("flex items-center gap-2", className)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex-1 bg-surface-muted rounded-full h-4">
|
||||
<div
|
||||
className="bg-brand h-full rounded-full transition-all duration-300"
|
||||
style={{ width: `${percent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[11px] text-text-primary font-bold">{label}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { ProgressBar, DiscreteBar, ProgressBarWithLabel }
|
||||
export type { ProgressBarProps, DiscreteBarProps, ProgressBarWithLabelProps }
|
||||
@@ -0,0 +1,94 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface RankedItem {
|
||||
rank: number
|
||||
name: string
|
||||
value: string | number
|
||||
isHighlighted?: boolean
|
||||
badge?: string
|
||||
}
|
||||
|
||||
interface RankedListProps extends React.ComponentProps<"div"> {
|
||||
title: string
|
||||
items: RankedItem[]
|
||||
footer?: React.ReactNode
|
||||
}
|
||||
|
||||
function RankedList({
|
||||
title,
|
||||
items,
|
||||
footer,
|
||||
className,
|
||||
...props
|
||||
}: RankedListProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="ranked-list"
|
||||
className={cn(
|
||||
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<h3 className="text-text-primary font-bold text-[18px] leading-snug mb-5">
|
||||
{title}
|
||||
</h3>
|
||||
|
||||
<div className="space-y-3">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
key={item.rank}
|
||||
className={cn(
|
||||
"flex items-center justify-between p-5 rounded-xl transition-all",
|
||||
item.isHighlighted
|
||||
? "bg-brand-tint border-2 border-brand"
|
||||
: "bg-surface-subtle",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div
|
||||
className={cn(
|
||||
"size-8 rounded-lg flex items-center justify-center text-[12px] font-bold",
|
||||
item.isHighlighted
|
||||
? "bg-brand text-white"
|
||||
: "bg-surface-muted text-text-tertiary",
|
||||
)}
|
||||
>
|
||||
{item.rank}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<p
|
||||
className={cn(
|
||||
"font-bold text-[14px]",
|
||||
item.isHighlighted ? "text-brand" : "text-text-primary",
|
||||
)}
|
||||
>
|
||||
{item.name}
|
||||
</p>
|
||||
{item.badge && (
|
||||
<span className="px-2 py-0.5 bg-brand text-white text-[9px] font-bold rounded uppercase tracking-wider">
|
||||
{item.badge}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-text-primary font-bold text-[17px]">
|
||||
{item.value}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{footer && (
|
||||
<p className="text-[12px] text-text-secondary text-center mt-5 font-medium">
|
||||
{footer}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { RankedList }
|
||||
export type { RankedListProps, RankedItem }
|
||||
@@ -0,0 +1,48 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface SectionCardProps extends React.ComponentProps<"div"> {
|
||||
title?: string
|
||||
headerRight?: React.ReactNode
|
||||
footer?: React.ReactNode
|
||||
}
|
||||
|
||||
function SectionCard({
|
||||
title,
|
||||
headerRight,
|
||||
footer,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: SectionCardProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="section-card"
|
||||
className={cn(
|
||||
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{(title || headerRight) && (
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
{title && (
|
||||
<h3 className="text-text-primary font-bold text-[18px] leading-snug">
|
||||
{title}
|
||||
</h3>
|
||||
)}
|
||||
{headerRight}
|
||||
</div>
|
||||
)}
|
||||
{children}
|
||||
{footer && (
|
||||
<div className="mt-5">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { SectionCard }
|
||||
export type { SectionCardProps }
|
||||
@@ -0,0 +1,74 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
import { TrendingUp, TrendingDown, type LucideIcon } from "lucide-react"
|
||||
|
||||
interface StatCardProps extends React.ComponentProps<"div"> {
|
||||
icon: LucideIcon
|
||||
label: string
|
||||
value: string | number
|
||||
unit?: string
|
||||
trend?: {
|
||||
value: string
|
||||
direction: "up" | "down"
|
||||
}
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
function StatCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
unit,
|
||||
trend,
|
||||
children,
|
||||
className,
|
||||
...props
|
||||
}: StatCardProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="stat-card"
|
||||
className={cn(
|
||||
"bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<div className="size-7 rounded-lg bg-brand/10 flex items-center justify-center">
|
||||
<Icon className="size-4 text-brand" strokeWidth={2} />
|
||||
</div>
|
||||
<p className="text-[12px] text-text-secondary font-medium uppercase tracking-[0.05em]">
|
||||
{label}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p className="text-text-primary text-[36px] font-bold leading-none tracking-[-0.02em] mb-3 whitespace-nowrap">
|
||||
{value}
|
||||
{unit && <span className="text-[18px] ms-0.5 tracking-normal">{unit}</span>}
|
||||
</p>
|
||||
|
||||
{trend && (
|
||||
<div className="flex items-center gap-1">
|
||||
<span
|
||||
className={cn(
|
||||
"text-[13px] font-bold",
|
||||
trend.direction === "up" ? "text-success" : "text-destructive",
|
||||
)}
|
||||
>
|
||||
{trend.value}
|
||||
</span>
|
||||
{trend.direction === "up" ? (
|
||||
<TrendingUp className="size-3.5 text-success" strokeWidth={2.5} />
|
||||
) : (
|
||||
<TrendingDown className="size-3.5 text-destructive" strokeWidth={2.5} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { StatCard }
|
||||
export type { StatCardProps }
|
||||
@@ -0,0 +1,68 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface TopBarProps extends React.ComponentProps<"header"> {
|
||||
logo?: React.ReactNode
|
||||
subtitle?: string
|
||||
actions?: React.ReactNode
|
||||
}
|
||||
|
||||
function TopBar({
|
||||
logo,
|
||||
subtitle,
|
||||
actions,
|
||||
className,
|
||||
...props
|
||||
}: TopBarProps) {
|
||||
return (
|
||||
<header
|
||||
data-slot="top-bar"
|
||||
className={cn("px-6 pt-8 pb-6", className)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">{logo}</div>
|
||||
{actions && (
|
||||
<div className="flex items-center gap-3">{actions}</div>
|
||||
)}
|
||||
</div>
|
||||
{subtitle && (
|
||||
<p className="text-[13px] text-text-tertiary font-medium mt-3">
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
</header>
|
||||
)
|
||||
}
|
||||
|
||||
interface TopBarActionProps extends React.ComponentProps<"button"> {
|
||||
badge?: boolean
|
||||
}
|
||||
|
||||
function TopBarAction({
|
||||
badge,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: TopBarActionProps) {
|
||||
return (
|
||||
<button
|
||||
data-slot="top-bar-action"
|
||||
className={cn(
|
||||
"relative size-10 rounded-full bg-card shadow-[var(--shadow-button)] flex items-center justify-center",
|
||||
"hover:shadow-[var(--shadow-card-hover)] transition-all",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{badge && (
|
||||
<span className="absolute top-1 right-1 size-1.5 bg-alert-badge rounded-full" />
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export { TopBar, TopBarAction }
|
||||
export type { TopBarProps, TopBarActionProps }
|
||||
@@ -0,0 +1,63 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "../ui/utils"
|
||||
|
||||
interface ValueDisplayProps extends React.ComponentProps<"div"> {
|
||||
value: number
|
||||
change?: number
|
||||
prefix?: string
|
||||
size?: "sm" | "md" | "lg"
|
||||
formatType?: "integer" | "decimal"
|
||||
showArrow?: boolean
|
||||
}
|
||||
|
||||
function ValueDisplay({
|
||||
value,
|
||||
change,
|
||||
prefix = "₩",
|
||||
size = "md",
|
||||
formatType = "integer",
|
||||
showArrow = true,
|
||||
className,
|
||||
...props
|
||||
}: ValueDisplayProps) {
|
||||
const formatValue = (n: number) => {
|
||||
if (formatType === "decimal") {
|
||||
return n.toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||
}
|
||||
return Math.round(n).toLocaleString("ko-KR")
|
||||
}
|
||||
|
||||
const sizeStyles = {
|
||||
sm: { value: "text-[16px] font-semibold leading-tight tracking-[-0.01em]", change: "text-[12px]" },
|
||||
md: { value: "text-[20px] font-semibold leading-tight tracking-[-0.02em]", change: "text-[14px]" },
|
||||
lg: { value: "text-[24px] font-bold leading-none tracking-[-0.02em]", change: "text-[14px]" },
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="value-display"
|
||||
className={cn("flex flex-col items-end justify-center min-w-20", className)}
|
||||
{...props}
|
||||
>
|
||||
<p className={cn("text-text-primary whitespace-nowrap", sizeStyles[size].value)}>
|
||||
{prefix}{formatValue(value)}
|
||||
</p>
|
||||
|
||||
{change !== undefined && change !== 0 && (
|
||||
<p
|
||||
className={cn(
|
||||
"flex items-center gap-0.5 whitespace-nowrap",
|
||||
sizeStyles[size].change,
|
||||
change > 0 ? "text-destructive" : "text-info",
|
||||
)}
|
||||
>
|
||||
{showArrow && <span>{change > 0 ? "▲" : "▼"}</span>}
|
||||
<span>{formatValue(Math.abs(change))}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { ValueDisplay }
|
||||
export type { ValueDisplayProps }
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Accordion({
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
|
||||
}
|
||||
|
||||
function AccordionItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
className={cn("border-b last:border-b-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AccordionTrigger({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
className={cn(
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
);
|
||||
}
|
||||
|
||||
function AccordionContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
{...props}
|
||||
>
|
||||
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
);
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||
@@ -0,0 +1,66 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
const alertVariants = cva(
|
||||
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-card text-card-foreground",
|
||||
destructive:
|
||||
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Alert({
|
||||
className,
|
||||
variant,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert"
|
||||
role="alert"
|
||||
className={cn(alertVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-title"
|
||||
className={cn(
|
||||
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn(
|
||||
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription };
|
||||
@@ -0,0 +1,53 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Avatar({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return (
|
||||
<AvatarPrimitive.Root
|
||||
data-slot="avatar"
|
||||
className={cn(
|
||||
"relative flex size-10 shrink-0 overflow-hidden rounded-full",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarImage({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return (
|
||||
<AvatarPrimitive.Image
|
||||
data-slot="avatar-image"
|
||||
className={cn("aspect-square size-full", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AvatarFallback({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn(
|
||||
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback };
|
||||
@@ -0,0 +1,46 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default:
|
||||
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||
secondary:
|
||||
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||
destructive:
|
||||
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline:
|
||||
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "span";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(badgeVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,71 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center whitespace-nowrap font-bold transition-colors duration-150 disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 shrink-0 outline-none focus-visible:ring-2 focus-visible:ring-brand/20",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
// 토스 스타일: brandSolid — 키컬러 배경, 흰 텍스트
|
||||
default:
|
||||
"bg-brand text-white active:bg-brand/85 disabled:bg-surface-muted disabled:text-text-disabled",
|
||||
// neutralSolid — 어두운 배경, 흰 텍스트
|
||||
neutral:
|
||||
"bg-[#2A2A2A] text-white active:bg-[#3C3C3C] disabled:bg-surface-muted disabled:text-text-disabled dark:bg-[#E0E0E0] dark:text-[#121212] dark:active:bg-[#C0C0C0]",
|
||||
// neutralWeak — 연한 회색 배경, 어두운 텍스트
|
||||
secondary:
|
||||
"bg-[#F3F4F5] text-text-primary active:bg-[#EAEBEC] disabled:bg-surface-muted disabled:text-text-disabled dark:bg-[#2B2E35] dark:text-[#E0E0E0] dark:active:bg-[#393D46]",
|
||||
// criticalSolid — 위험 액션
|
||||
destructive:
|
||||
"bg-destructive text-white active:bg-destructive/85 focus-visible:ring-destructive/20 disabled:bg-surface-muted disabled:text-text-disabled",
|
||||
// outline — 테두리만
|
||||
outline:
|
||||
"border border-border bg-transparent text-text-primary active:bg-surface-muted/50 disabled:border-surface-muted disabled:text-text-disabled dark:border-white/8",
|
||||
// ghost — 배경/테두리 없음
|
||||
ghost:
|
||||
"bg-transparent text-text-primary active:bg-surface-muted/50 disabled:text-text-disabled",
|
||||
// brandGhost — 키컬러 텍스트, 배경 없음
|
||||
brandGhost:
|
||||
"bg-transparent text-brand active:bg-brand/8 disabled:text-text-disabled",
|
||||
},
|
||||
size: {
|
||||
// 토스 기준 4단계: xsmall(32) / small(36) / medium(40) / large(52)
|
||||
xs: "h-8 px-3.5 gap-1 text-[13px] rounded-full [&_svg:not([class*='size-'])]:size-3.5",
|
||||
sm: "h-9 px-3.5 gap-1 text-[14px] rounded-lg [&_svg:not([class*='size-'])]:size-3.5",
|
||||
md: "h-10 px-4 gap-1.5 text-[14px] rounded-lg [&_svg:not([class*='size-'])]:size-4",
|
||||
lg: "h-[52px] px-5 gap-2 text-[18px] rounded-xl [&_svg:not([class*='size-'])]:size-[22px]",
|
||||
icon: "size-10 rounded-full [&_svg:not([class*='size-'])]:size-[18px]",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "md",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1,92 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<h4
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<p
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6 [&:last-child]:pb-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 pb-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Checkbox({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
return (
|
||||
<CheckboxPrimitive.Root
|
||||
data-slot="checkbox"
|
||||
className={cn(
|
||||
"peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<CheckboxPrimitive.Indicator
|
||||
data-slot="checkbox-indicator"
|
||||
className="flex items-center justify-center text-current transition-none"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
</CheckboxPrimitive.Indicator>
|
||||
</CheckboxPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Checkbox };
|
||||
@@ -0,0 +1,83 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "./utils"
|
||||
|
||||
interface ConfirmModalProps extends React.ComponentProps<"div"> {
|
||||
isOpen: boolean
|
||||
onConfirm: () => void
|
||||
onCancel: () => void
|
||||
title: string
|
||||
message: string | string[]
|
||||
confirmText?: string
|
||||
cancelText?: string
|
||||
variant?: "default" | "destructive"
|
||||
}
|
||||
|
||||
function ConfirmModal({
|
||||
isOpen,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
title,
|
||||
message,
|
||||
confirmText = "확인",
|
||||
cancelText = "닫기",
|
||||
variant = "default",
|
||||
className,
|
||||
...props
|
||||
}: ConfirmModalProps) {
|
||||
const messages = Array.isArray(message) ? message : [message]
|
||||
|
||||
if (!isOpen) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
data-slot="confirm-modal"
|
||||
className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50"
|
||||
onClick={onCancel}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"bg-card rounded-2xl p-5 mx-4 max-w-sm w-full shadow-[var(--shadow-modal)]",
|
||||
className,
|
||||
)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex flex-col gap-5 items-center text-center">
|
||||
{/* Content */}
|
||||
<div className="flex flex-col gap-2 items-center w-full">
|
||||
<h3 className="text-text-primary text-[16px] font-semibold leading-tight tracking-[-0.01em]">
|
||||
{title}
|
||||
</h3>
|
||||
<div className="text-text-secondary text-[14px] leading-normal">
|
||||
{messages.map((line, i) => (
|
||||
<p key={i}>{line}</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Buttons — 토스 규칙: 좌측=닫기, 우측=확인 */}
|
||||
<div className="flex gap-2 w-full">
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="flex-1 h-11 rounded-full text-[16px] font-semibold border border-brand text-brand bg-card active:bg-brand/8 transition-colors duration-150"
|
||||
>
|
||||
{cancelText}
|
||||
</button>
|
||||
<button
|
||||
onClick={onConfirm}
|
||||
className={cn(
|
||||
"flex-1 h-11 rounded-full text-[16px] font-semibold text-white active:opacity-85 transition-colors duration-150",
|
||||
variant === "destructive" ? "bg-destructive" : "bg-brand",
|
||||
)}
|
||||
>
|
||||
{confirmText}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { ConfirmModal }
|
||||
export type { ConfirmModalProps }
|
||||
@@ -0,0 +1,47 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "./utils"
|
||||
|
||||
interface DataDisplayProps extends React.ComponentProps<"div"> {
|
||||
label: string
|
||||
value: string | number
|
||||
icon?: React.ReactNode
|
||||
highlighted?: boolean
|
||||
}
|
||||
|
||||
function DataDisplay({
|
||||
label,
|
||||
value,
|
||||
icon,
|
||||
highlighted = false,
|
||||
className,
|
||||
...props
|
||||
}: DataDisplayProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="data-display"
|
||||
className={cn(
|
||||
"flex items-center gap-2 px-4 py-3 bg-card rounded-lg border border-surface-muted min-h-12",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{icon && (
|
||||
<div className="size-6 text-brand shrink-0">{icon}</div>
|
||||
)}
|
||||
<span className="text-[12px] font-medium text-text-secondary min-w-20">
|
||||
{label}
|
||||
</span>
|
||||
<span
|
||||
className={cn(
|
||||
"text-[14px] font-semibold flex-1",
|
||||
highlighted ? "text-brand" : "text-text-primary",
|
||||
)}
|
||||
>
|
||||
{typeof value === "number" ? value.toLocaleString("ko-KR") : value}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { DataDisplay }
|
||||
export type { DataDisplayProps }
|
||||
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Dialog({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content>) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
|
||||
<XIcon />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogPrimitive.Close>
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-header"
|
||||
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="dialog-footer"
|
||||
className={cn(
|
||||
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return (
|
||||
<DialogPrimitive.Title
|
||||
data-slot="dialog-title"
|
||||
className={cn("text-lg leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return (
|
||||
<DialogPrimitive.Description
|
||||
data-slot="dialog-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogOverlay,
|
||||
DialogPortal,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "./utils"
|
||||
|
||||
interface DrawerProps extends React.ComponentProps<"div"> {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
title: string
|
||||
position?: "left" | "right"
|
||||
width?: string
|
||||
footer?: React.ReactNode
|
||||
}
|
||||
|
||||
function Drawer({
|
||||
isOpen,
|
||||
onClose,
|
||||
title,
|
||||
position = "right",
|
||||
width = "w-80",
|
||||
footer,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: DrawerProps) {
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop */}
|
||||
<div
|
||||
className={cn(
|
||||
"fixed inset-0 bg-black/40 backdrop-blur-sm z-40 transition-opacity duration-[var(--duration-normal)]",
|
||||
isOpen ? "opacity-100" : "opacity-0 pointer-events-none",
|
||||
)}
|
||||
onClick={onClose}
|
||||
/>
|
||||
|
||||
{/* Panel */}
|
||||
<div
|
||||
data-slot="drawer"
|
||||
className={cn(
|
||||
"fixed top-0 h-full bg-card shadow-[var(--shadow-modal)] z-50",
|
||||
"transform transition-transform duration-[var(--duration-moderate)]",
|
||||
width,
|
||||
position === "right" && "right-0",
|
||||
position === "left" && "left-0",
|
||||
position === "right" && (isOpen ? "translate-x-0" : "translate-x-full"),
|
||||
position === "left" && (isOpen ? "translate-x-0" : "-translate-x-full"),
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="flex flex-col h-full">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-6 py-4 border-b border-surface-muted shrink-0">
|
||||
<h2 className="text-text-primary font-bold text-[18px] leading-snug">
|
||||
{title}
|
||||
</h2>
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="size-8 flex items-center justify-center rounded-lg active:bg-surface-muted/50 transition-colors"
|
||||
>
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" className="text-text-primary">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 p-6 overflow-y-auto">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
{/* Footer */}
|
||||
{footer && (
|
||||
<div className="px-6 py-4 border-t border-surface-muted shrink-0">
|
||||
{footer}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export { Drawer }
|
||||
export type { DrawerProps }
|
||||
@@ -0,0 +1,257 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
};
|
||||
@@ -0,0 +1,168 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import {
|
||||
Controller,
|
||||
FormProvider,
|
||||
useFormContext,
|
||||
useFormState,
|
||||
type ControllerProps,
|
||||
type FieldPath,
|
||||
type FieldValues,
|
||||
} from "react-hook-form";
|
||||
|
||||
import { cn } from "./utils";
|
||||
import { Label } from "./label";
|
||||
|
||||
const Form = FormProvider;
|
||||
|
||||
type FormFieldContextValue<
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
> = {
|
||||
name: TName;
|
||||
};
|
||||
|
||||
const FormFieldContext = React.createContext<FormFieldContextValue>(
|
||||
{} as FormFieldContextValue,
|
||||
);
|
||||
|
||||
const FormField = <
|
||||
TFieldValues extends FieldValues = FieldValues,
|
||||
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
|
||||
>({
|
||||
...props
|
||||
}: ControllerProps<TFieldValues, TName>) => {
|
||||
return (
|
||||
<FormFieldContext.Provider value={{ name: props.name }}>
|
||||
<Controller {...props} />
|
||||
</FormFieldContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
const useFormField = () => {
|
||||
const fieldContext = React.useContext(FormFieldContext);
|
||||
const itemContext = React.useContext(FormItemContext);
|
||||
const { getFieldState } = useFormContext();
|
||||
const formState = useFormState({ name: fieldContext.name });
|
||||
const fieldState = getFieldState(fieldContext.name, formState);
|
||||
|
||||
if (!fieldContext) {
|
||||
throw new Error("useFormField should be used within <FormField>");
|
||||
}
|
||||
|
||||
const { id } = itemContext;
|
||||
|
||||
return {
|
||||
id,
|
||||
name: fieldContext.name,
|
||||
formItemId: `${id}-form-item`,
|
||||
formDescriptionId: `${id}-form-item-description`,
|
||||
formMessageId: `${id}-form-item-message`,
|
||||
...fieldState,
|
||||
};
|
||||
};
|
||||
|
||||
type FormItemContextValue = {
|
||||
id: string;
|
||||
};
|
||||
|
||||
const FormItemContext = React.createContext<FormItemContextValue>(
|
||||
{} as FormItemContextValue,
|
||||
);
|
||||
|
||||
function FormItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const id = React.useId();
|
||||
|
||||
return (
|
||||
<FormItemContext.Provider value={{ id }}>
|
||||
<div
|
||||
data-slot="form-item"
|
||||
className={cn("grid gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
</FormItemContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
function FormLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
const { error, formItemId } = useFormField();
|
||||
|
||||
return (
|
||||
<Label
|
||||
data-slot="form-label"
|
||||
data-error={!!error}
|
||||
className={cn("data-[error=true]:text-destructive", className)}
|
||||
htmlFor={formItemId}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FormControl({ ...props }: React.ComponentProps<typeof Slot>) {
|
||||
const { error, formItemId, formDescriptionId, formMessageId } =
|
||||
useFormField();
|
||||
|
||||
return (
|
||||
<Slot
|
||||
data-slot="form-control"
|
||||
id={formItemId}
|
||||
aria-describedby={
|
||||
!error
|
||||
? `${formDescriptionId}`
|
||||
: `${formDescriptionId} ${formMessageId}`
|
||||
}
|
||||
aria-invalid={!!error}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FormDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { formDescriptionId } = useFormField();
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-description"
|
||||
id={formDescriptionId}
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function FormMessage({ className, ...props }: React.ComponentProps<"p">) {
|
||||
const { error, formMessageId } = useFormField();
|
||||
const body = error ? String(error?.message ?? "") : props.children;
|
||||
|
||||
if (!body) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<p
|
||||
data-slot="form-message"
|
||||
id={formMessageId}
|
||||
className={cn("text-destructive text-sm", className)}
|
||||
{...props}
|
||||
>
|
||||
{body}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
useFormField,
|
||||
Form,
|
||||
FormItem,
|
||||
FormLabel,
|
||||
FormControl,
|
||||
FormDescription,
|
||||
FormMessage,
|
||||
FormField,
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
|
||||
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Input };
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as LabelPrimitive from "@radix-ui/react-label";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Label };
|
||||
@@ -0,0 +1,285 @@
|
||||
/**
|
||||
* StyleSeed — Motion Primitives (Framer Motion)
|
||||
*
|
||||
* Pre-configured animation wrappers that follow the design language.
|
||||
* Install: npm install framer-motion
|
||||
*/
|
||||
import * as React from "react"
|
||||
import { motion, AnimatePresence, type Variants } from "framer-motion"
|
||||
import { cn } from "./utils"
|
||||
|
||||
// ── Duration & Easing Tokens ────────────────────────
|
||||
|
||||
export const duration = {
|
||||
fast: 0.1,
|
||||
normal: 0.2,
|
||||
moderate: 0.3,
|
||||
slow: 0.35,
|
||||
} as const
|
||||
|
||||
export const ease = {
|
||||
default: [0.25, 0.1, 0.25, 1.0],
|
||||
in: [0.4, 0, 1, 1],
|
||||
out: [0, 0, 0.2, 1],
|
||||
spring: { type: "spring" as const, damping: 25, stiffness: 300 },
|
||||
} as const
|
||||
|
||||
// ── Preset Variants ─────────────────────────────────
|
||||
|
||||
export const fadeIn: Variants = {
|
||||
hidden: { opacity: 0 },
|
||||
visible: { opacity: 1 },
|
||||
exit: { opacity: 0 },
|
||||
}
|
||||
|
||||
export const fadeUp: Variants = {
|
||||
hidden: { opacity: 0, y: 12 },
|
||||
visible: { opacity: 1, y: 0 },
|
||||
exit: { opacity: 0, y: 12 },
|
||||
}
|
||||
|
||||
export const slideUp: Variants = {
|
||||
hidden: { opacity: 0, y: "100%" },
|
||||
visible: { opacity: 1, y: 0 },
|
||||
exit: { opacity: 0, y: "100%" },
|
||||
}
|
||||
|
||||
export const slideRight: Variants = {
|
||||
hidden: { x: "100%" },
|
||||
visible: { x: 0 },
|
||||
exit: { x: "100%" },
|
||||
}
|
||||
|
||||
export const scaleIn: Variants = {
|
||||
hidden: { opacity: 0, scale: 0.95 },
|
||||
visible: { opacity: 1, scale: 1 },
|
||||
exit: { opacity: 0, scale: 0.95 },
|
||||
}
|
||||
|
||||
// ── FadeIn ──────────────────────────────────────────
|
||||
|
||||
interface FadeInProps extends React.ComponentProps<typeof motion.div> {
|
||||
delay?: number
|
||||
}
|
||||
|
||||
function FadeIn({ delay = 0, className, children, ...props }: FadeInProps) {
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="fade-in"
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
variants={fadeIn}
|
||||
transition={{ duration: duration.normal, delay }}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── FadeUp (Card entry animation) ───────────────────
|
||||
|
||||
interface FadeUpProps extends React.ComponentProps<typeof motion.div> {
|
||||
delay?: number
|
||||
}
|
||||
|
||||
function FadeUp({ delay = 0, className, children, ...props }: FadeUpProps) {
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="fade-up"
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
variants={fadeUp}
|
||||
transition={{ duration: duration.normal, delay, ease: ease.out }}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Stagger (Card grid entry) ───────────────────────
|
||||
|
||||
interface StaggerProps extends React.ComponentProps<typeof motion.div> {
|
||||
staggerDelay?: number
|
||||
}
|
||||
|
||||
function Stagger({ staggerDelay = 0.05, className, children, ...props }: StaggerProps) {
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="stagger"
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
variants={{
|
||||
hidden: {},
|
||||
visible: { transition: { staggerChildren: staggerDelay } },
|
||||
}}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
function StaggerItem({ className, children, ...props }: React.ComponentProps<typeof motion.div>) {
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="stagger-item"
|
||||
variants={fadeUp}
|
||||
transition={{ duration: duration.normal, ease: ease.out }}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── PresenceModal (Modal/Sheet enter + exit) ────────
|
||||
|
||||
interface PresenceModalProps {
|
||||
isOpen: boolean
|
||||
children: React.ReactNode
|
||||
variant?: "fade" | "slideUp" | "scale"
|
||||
className?: string
|
||||
}
|
||||
|
||||
function PresenceModal({ isOpen, children, variant = "fade", className }: PresenceModalProps) {
|
||||
const variants = {
|
||||
fade: fadeIn,
|
||||
slideUp: slideUp,
|
||||
scale: scaleIn,
|
||||
}
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
data-slot="presence-modal"
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
exit="exit"
|
||||
variants={variants[variant]}
|
||||
transition={{
|
||||
duration: variant === "slideUp" ? duration.moderate : duration.normal,
|
||||
ease: ease.out,
|
||||
}}
|
||||
className={cn(className)}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
|
||||
// ── Backdrop ────────────────────────────────────────
|
||||
|
||||
interface BackdropProps {
|
||||
isOpen: boolean
|
||||
onClick?: () => void
|
||||
className?: string
|
||||
}
|
||||
|
||||
function Backdrop({ isOpen, onClick, className }: BackdropProps) {
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<motion.div
|
||||
data-slot="backdrop"
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
transition={{ duration: duration.normal }}
|
||||
onClick={onClick}
|
||||
className={cn("fixed inset-0 bg-black/40 backdrop-blur-sm z-40", className)}
|
||||
/>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
)
|
||||
}
|
||||
|
||||
// ── PageTransition (Page entry stagger) ─────────────
|
||||
|
||||
function PageTransition({ className, children, ...props }: React.ComponentProps<typeof motion.div>) {
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="page-transition"
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
variants={{
|
||||
hidden: {},
|
||||
visible: { transition: { staggerChildren: 0.05 } },
|
||||
}}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
function PageSection({ className, children, ...props }: React.ComponentProps<typeof motion.div>) {
|
||||
return (
|
||||
<motion.div
|
||||
data-slot="page-section"
|
||||
variants={fadeUp}
|
||||
transition={{ duration: duration.normal, ease: ease.out }}
|
||||
className={cn(className)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</motion.div>
|
||||
)
|
||||
}
|
||||
|
||||
// ── NumberCounter (Hero metric counting) ────────────
|
||||
|
||||
interface NumberCounterProps {
|
||||
value: number
|
||||
duration?: number
|
||||
className?: string
|
||||
}
|
||||
|
||||
function NumberCounter({ value, duration: d = 0.6, className }: NumberCounterProps) {
|
||||
const [display, setDisplay] = React.useState(0)
|
||||
const prefersReducedMotion = React.useRef(
|
||||
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (prefersReducedMotion.current) {
|
||||
setDisplay(value)
|
||||
return
|
||||
}
|
||||
|
||||
const startTime = performance.now()
|
||||
|
||||
function step(currentTime: number) {
|
||||
const elapsed = (currentTime - startTime) / 1000
|
||||
const progress = Math.min(elapsed / d, 1)
|
||||
const eased = 1 - Math.pow(1 - progress, 3) // ease-out cubic
|
||||
setDisplay(Math.round(eased * value))
|
||||
if (progress < 1) requestAnimationFrame(step)
|
||||
}
|
||||
|
||||
requestAnimationFrame(step)
|
||||
}, [value, d])
|
||||
|
||||
return <span data-slot="number-counter" className={className}>{display.toLocaleString()}</span>
|
||||
}
|
||||
|
||||
export {
|
||||
FadeIn,
|
||||
FadeUp,
|
||||
Stagger,
|
||||
StaggerItem,
|
||||
PresenceModal,
|
||||
Backdrop,
|
||||
PageTransition,
|
||||
PageSection,
|
||||
NumberCounter,
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as PopoverPrimitive from "@radix-ui/react-popover";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Popover({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
|
||||
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
|
||||
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function PopoverContent({
|
||||
className,
|
||||
align = "center",
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
<PopoverPrimitive.Portal>
|
||||
<PopoverPrimitive.Content
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</PopoverPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function PopoverAnchor({
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
|
||||
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
|
||||
}
|
||||
|
||||
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ProgressPrimitive from "@radix-ui/react-progress";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Progress({
|
||||
className,
|
||||
value,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
|
||||
return (
|
||||
<ProgressPrimitive.Root
|
||||
data-slot="progress"
|
||||
className={cn(
|
||||
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ProgressPrimitive.Indicator
|
||||
data-slot="progress-indicator"
|
||||
className="bg-primary h-full w-full flex-1 transition-all"
|
||||
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
|
||||
/>
|
||||
</ProgressPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Progress };
|
||||
@@ -0,0 +1,45 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group";
|
||||
import { CircleIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function RadioGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Root
|
||||
data-slot="radio-group"
|
||||
className={cn("grid gap-3", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function RadioGroupItem({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
|
||||
return (
|
||||
<RadioGroupPrimitive.Item
|
||||
data-slot="radio-group-item"
|
||||
className={cn(
|
||||
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<RadioGroupPrimitive.Indicator
|
||||
data-slot="radio-group-indicator"
|
||||
className="relative flex items-center justify-center"
|
||||
>
|
||||
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
|
||||
</RadioGroupPrimitive.Indicator>
|
||||
</RadioGroupPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
export { RadioGroup, RadioGroupItem };
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function ScrollArea({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root
|
||||
data-slot="scroll-area"
|
||||
className={cn("relative", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Viewport
|
||||
data-slot="scroll-area-viewport"
|
||||
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
|
||||
>
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({
|
||||
className,
|
||||
orientation = "vertical",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
data-slot="scroll-area-scrollbar"
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"flex touch-none p-px transition-colors select-none",
|
||||
orientation === "vertical" &&
|
||||
"h-full w-2.5 border-l border-l-transparent",
|
||||
orientation === "horizontal" &&
|
||||
"h-2.5 flex-col border-t border-t-transparent",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb
|
||||
data-slot="scroll-area-thumb"
|
||||
className="bg-border relative flex-1 rounded-full"
|
||||
/>
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -0,0 +1,54 @@
|
||||
import * as React from "react"
|
||||
import { cn } from "./utils"
|
||||
|
||||
interface SegmentedControlProps extends Omit<React.ComponentProps<"div">, "onChange"> {
|
||||
segments: string[]
|
||||
activeIndex: number
|
||||
onChange?: (index: number) => void
|
||||
size?: "sm" | "md"
|
||||
}
|
||||
|
||||
function SegmentedControl({
|
||||
segments,
|
||||
activeIndex,
|
||||
onChange,
|
||||
size = "md",
|
||||
className,
|
||||
...props
|
||||
}: SegmentedControlProps) {
|
||||
return (
|
||||
<div
|
||||
data-slot="segmented-control"
|
||||
className={cn(
|
||||
"flex items-center bg-surface-muted w-full",
|
||||
size === "sm" ? "p-0.5 gap-0.5 rounded-lg" : "p-1 gap-1 rounded-xl",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{segments.map((segment, index) => {
|
||||
const isActive = index === activeIndex
|
||||
return (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => onChange?.(index)}
|
||||
className={cn(
|
||||
"flex-1 flex items-center justify-center font-medium transition-all duration-150",
|
||||
size === "sm"
|
||||
? "h-7 text-[12px] rounded-md"
|
||||
: "h-9 text-[14px] rounded-lg",
|
||||
isActive
|
||||
? "bg-card text-text-primary shadow-[var(--shadow-card)]"
|
||||
: "bg-transparent text-text-disabled",
|
||||
)}
|
||||
>
|
||||
{segment}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export { SegmentedControl }
|
||||
export type { SegmentedControlProps }
|
||||
@@ -0,0 +1,189 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SelectPrimitive from "@radix-ui/react-select";
|
||||
import {
|
||||
CheckIcon,
|
||||
ChevronDownIcon,
|
||||
ChevronUpIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-full items-center justify-between gap-2 rounded-md border bg-input-background px-3 py-2 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator-root"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,139 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SheetPrimitive from "@radix-ui/react-dialog";
|
||||
import { XIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||
}
|
||||
|
||||
function SheetTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function SheetClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
||||
}
|
||||
|
||||
function SheetPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
|
||||
}
|
||||
|
||||
function SheetOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
|
||||
return (
|
||||
<SheetPrimitive.Overlay
|
||||
data-slot="sheet-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetContent({
|
||||
className,
|
||||
children,
|
||||
side = "right",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||
side?: "top" | "right" | "bottom" | "left";
|
||||
}) {
|
||||
return (
|
||||
<SheetPortal>
|
||||
<SheetOverlay />
|
||||
<SheetPrimitive.Content
|
||||
data-slot="sheet-content"
|
||||
className={cn(
|
||||
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
|
||||
side === "right" &&
|
||||
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
|
||||
side === "left" &&
|
||||
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
|
||||
side === "top" &&
|
||||
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
|
||||
side === "bottom" &&
|
||||
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
|
||||
<XIcon className="size-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</SheetPrimitive.Close>
|
||||
</SheetPrimitive.Content>
|
||||
</SheetPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="sheet-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||
return (
|
||||
<SheetPrimitive.Title
|
||||
data-slot="sheet-title"
|
||||
className={cn("text-foreground font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
|
||||
return (
|
||||
<SheetPrimitive.Description
|
||||
data-slot="sheet-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Sheet,
|
||||
SheetTrigger,
|
||||
SheetClose,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetFooter,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="skeleton"
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Skeleton };
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as SwitchPrimitive from "@radix-ui/react-switch";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Switch({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SwitchPrimitive.Root>) {
|
||||
return (
|
||||
<SwitchPrimitive.Root
|
||||
data-slot="switch"
|
||||
className={cn(
|
||||
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-switch-background focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<SwitchPrimitive.Thumb
|
||||
data-slot="switch-thumb"
|
||||
className={cn(
|
||||
"bg-card dark:data-[state=unchecked]:bg-card-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0",
|
||||
)}
|
||||
/>
|
||||
</SwitchPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Switch };
|
||||
@@ -0,0 +1,116 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Table({ className, ...props }: React.ComponentProps<"table">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="table-container"
|
||||
className="relative w-full overflow-x-auto"
|
||||
>
|
||||
<table
|
||||
data-slot="table"
|
||||
className={cn("w-full caption-bottom text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
|
||||
return (
|
||||
<thead
|
||||
data-slot="table-header"
|
||||
className={cn("[&_tr]:border-b", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
|
||||
return (
|
||||
<tbody
|
||||
data-slot="table-body"
|
||||
className={cn("[&_tr:last-child]:border-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
|
||||
return (
|
||||
<tfoot
|
||||
data-slot="table-footer"
|
||||
className={cn(
|
||||
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
|
||||
return (
|
||||
<tr
|
||||
data-slot="table-row"
|
||||
className={cn(
|
||||
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
|
||||
return (
|
||||
<th
|
||||
data-slot="table-head"
|
||||
className={cn(
|
||||
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
|
||||
return (
|
||||
<td
|
||||
data-slot="table-cell"
|
||||
className={cn(
|
||||
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TableCaption({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"caption">) {
|
||||
return (
|
||||
<caption
|
||||
data-slot="table-caption"
|
||||
className={cn("text-muted-foreground mt-4 text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableBody,
|
||||
TableFooter,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TableCell,
|
||||
TableCaption,
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Tabs({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return (
|
||||
<TabsPrimitive.Root
|
||||
data-slot="tabs"
|
||||
className={cn("flex flex-col gap-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsList({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
data-slot="tabs-list"
|
||||
className={cn(
|
||||
"bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-xl p-[3px] flex",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsTrigger({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
data-slot="tabs-trigger"
|
||||
className={cn(
|
||||
"data-[state=active]:bg-card dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-xl border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return (
|
||||
<TabsPrimitive.Content
|
||||
data-slot="tabs-content"
|
||||
className={cn("flex-1 outline-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
@@ -0,0 +1,18 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
|
||||
return (
|
||||
<textarea
|
||||
data-slot="textarea"
|
||||
className={cn(
|
||||
"resize-none border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-input-background px-3 py-2 text-base transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Textarea };
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
|
||||
import { type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "./utils";
|
||||
import { toggleVariants } from "./toggle";
|
||||
|
||||
const ToggleGroupContext = React.createContext<
|
||||
VariantProps<typeof toggleVariants>
|
||||
>({
|
||||
size: "default",
|
||||
variant: "default",
|
||||
});
|
||||
|
||||
function ToggleGroup({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<ToggleGroupPrimitive.Root
|
||||
data-slot="toggle-group"
|
||||
data-variant={variant}
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"group/toggle-group flex w-fit items-center rounded-md data-[variant=outline]:shadow-xs",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ToggleGroupContext.Provider value={{ variant, size }}>
|
||||
{children}
|
||||
</ToggleGroupContext.Provider>
|
||||
</ToggleGroupPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ToggleGroupItem({
|
||||
className,
|
||||
children,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ToggleGroupPrimitive.Item> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
const context = React.useContext(ToggleGroupContext);
|
||||
|
||||
return (
|
||||
<ToggleGroupPrimitive.Item
|
||||
data-slot="toggle-group-item"
|
||||
data-variant={context.variant || variant}
|
||||
data-size={context.size || size}
|
||||
className={cn(
|
||||
toggleVariants({
|
||||
variant: context.variant || variant,
|
||||
size: context.size || size,
|
||||
}),
|
||||
"min-w-0 flex-1 shrink-0 rounded-none shadow-none first:rounded-l-md last:rounded-r-md focus:z-10 focus-visible:z-10 data-[variant=outline]:border-l-0 data-[variant=outline]:first:border-l",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</ToggleGroupPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
export { ToggleGroup, ToggleGroupItem };
|
||||
@@ -0,0 +1,47 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as TogglePrimitive from "@radix-ui/react-toggle";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
const toggleVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
outline:
|
||||
"border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-2 min-w-9",
|
||||
sm: "h-8 px-1.5 min-w-8",
|
||||
lg: "h-10 px-2.5 min-w-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
function Toggle({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TogglePrimitive.Root> &
|
||||
VariantProps<typeof toggleVariants>) {
|
||||
return (
|
||||
<TogglePrimitive.Root
|
||||
data-slot="toggle"
|
||||
className={cn(toggleVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Toggle, toggleVariants };
|
||||
@@ -0,0 +1,61 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
|
||||
|
||||
import { cn } from "./utils";
|
||||
|
||||
function TooltipProvider({
|
||||
delayDuration = 0,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
|
||||
return (
|
||||
<TooltipPrimitive.Provider
|
||||
data-slot="tooltip-provider"
|
||||
delayDuration={delayDuration}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Tooltip({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function TooltipTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
|
||||
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function TooltipContent({
|
||||
className,
|
||||
sideOffset = 0,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
|
||||
return (
|
||||
<TooltipPrimitive.Portal>
|
||||
<TooltipPrimitive.Content
|
||||
data-slot="tooltip-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
|
||||
</TooltipPrimitive.Content>
|
||||
</TooltipPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };
|
||||
@@ -0,0 +1,6 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
|
||||
html {
|
||||
font-size: var(--font-size);
|
||||
color-scheme: light dark;
|
||||
scroll-behavior: smooth;
|
||||
scroll-padding-top: 4rem;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: var(--text-2xl);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1.35;
|
||||
letter-spacing: -0.01em;
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: var(--text-xl);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1.35;
|
||||
letter-spacing: -0.01em;
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
h3 {
|
||||
font-size: var(--text-lg);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1.35;
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
h4 {
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
label {
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
button {
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--font-weight-medium);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
input {
|
||||
font-size: var(--text-base);
|
||||
font-weight: var(--font-weight-normal);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
p {
|
||||
text-wrap: pretty;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background-color: var(--brand);
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Accessibility: Reduced Motion === */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
*, *::before, *::after {
|
||||
animation-duration: 0.01ms !important;
|
||||
animation-iteration-count: 1 !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
scroll-behavior: auto !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Accessibility: Screen Reader Only === */
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border-width: 0;
|
||||
}
|
||||
|
||||
/* === Safe Area Insets === */
|
||||
.pb-safe {
|
||||
padding-bottom: env(safe-area-inset-bottom, 0px);
|
||||
}
|
||||
|
||||
.pt-safe {
|
||||
padding-top: env(safe-area-inset-top, 0px);
|
||||
}
|
||||
|
||||
.px-safe {
|
||||
padding-left: env(safe-area-inset-left, 0px);
|
||||
padding-right: env(safe-area-inset-right, 0px);
|
||||
}
|
||||
|
||||
/* === Utility: Hide Scrollbar === */
|
||||
.scrollbar-hide {
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.scrollbar-hide::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* === Utility: Touch Target Minimum === */
|
||||
.touch-target {
|
||||
min-height: 44px;
|
||||
min-width: 44px;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
/* StyleSeed - Font Imports */
|
||||
/* Inter: Latin/digits · Pretendard Variable: Korean (falls through from Inter) */
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
|
||||
@import url('https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css');
|
||||
|
||||
body {
|
||||
font-family: 'Inter', 'Pretendard Variable', Pretendard, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
@import './fonts.css';
|
||||
@import 'tailwindcss';
|
||||
@import 'tw-animate-css';
|
||||
@import './theme.css';
|
||||
@import './base.css';
|
||||
@@ -0,0 +1,234 @@
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--font-size: 16px;
|
||||
|
||||
/* === CUSTOMIZE: Brand Colors === */
|
||||
--brand: #FF4D53; /* oklch(0.708 0.234 24) coral red */
|
||||
--primary: rgba(0,0,0,0.95);
|
||||
--primary-foreground: #ffffff;
|
||||
|
||||
/* === Surface & Background === */
|
||||
--background: #ffffff;
|
||||
--foreground: rgba(0,0,0,0.95);
|
||||
--card: #ffffff;
|
||||
--card-foreground: rgba(0,0,0,0.95);
|
||||
--popover: #ffffff;
|
||||
--popover-foreground: rgba(0,0,0,0.95);
|
||||
|
||||
/* === Secondary & Muted === */
|
||||
--secondary: #f6f5f4;
|
||||
--secondary-foreground: #31302e;
|
||||
--muted: #e8e5e1;
|
||||
--muted-foreground: #615d59;
|
||||
--accent: #f6f5f4;
|
||||
--accent-foreground: #31302e;
|
||||
|
||||
/* === Status Colors === */
|
||||
--destructive: #dd5b00;
|
||||
--destructive-foreground: #ffffff;
|
||||
--success: #2a9d99;
|
||||
--success-foreground: #ffffff;
|
||||
--warning: #dd5b00;
|
||||
--warning-foreground: #ffffff;
|
||||
--info: #0075de;
|
||||
--info-foreground: #ffffff;
|
||||
|
||||
/* === Text Hierarchy === */
|
||||
--text-primary: rgba(0,0,0,0.95);
|
||||
--text-secondary: #615d59;
|
||||
--text-tertiary: #a39e98;
|
||||
--text-disabled: #c4c0bb;
|
||||
--icon-default: #615d59;
|
||||
|
||||
/* === Surface Colors === */
|
||||
--surface-page: #ffffff;
|
||||
--surface-subtle: #f6f5f4;
|
||||
--surface-muted: #e8e5e1;
|
||||
--brand-tint: #FFE6E3;
|
||||
--alert-badge: #dd5b00;
|
||||
|
||||
/* === Borders & Inputs === */
|
||||
--border: rgba(0,0,0,0.1);
|
||||
--input: transparent;
|
||||
--input-background: #f6f5f4;
|
||||
--switch-background: #c4c0bb;
|
||||
|
||||
/* === Typography === */
|
||||
--font-weight-medium: 500;
|
||||
--font-weight-normal: 400;
|
||||
|
||||
/* === Focus Ring === */
|
||||
--ring: #FF4D53;
|
||||
|
||||
/* === Chart Colors === */
|
||||
--chart-1: #FF4D53;
|
||||
--chart-2: #2a9d99;
|
||||
--chart-3: #ff64c8;
|
||||
--chart-4: #dd5b00;
|
||||
--chart-5: #213183;
|
||||
|
||||
/* === Radius === */
|
||||
--radius: 0.5rem;
|
||||
|
||||
/* === Shadows === */
|
||||
--shadow-card: rgba(0,0,0,0.04) 0px 4px 18px, rgba(0,0,0,0.027) 0px 2px 7.85px, rgba(0,0,0,0.02) 0px 0.8px 2.93px, rgba(0,0,0,0.01) 0px 0.175px 1.04px;
|
||||
--shadow-button: 0 1px 2px rgba(0,0,0,0.04);
|
||||
--shadow-card-hover: rgba(0,0,0,0.06) 0px 6px 20px, rgba(0,0,0,0.04) 0px 3px 10px;
|
||||
--shadow-elevated: rgba(0,0,0,0.04) 0px 7px 15px, rgba(0,0,0,0.02) 0px 3px 7px, rgba(0,0,0,0.01) 0px 1px 3px;
|
||||
--shadow-modal: rgba(0,0,0,0.05) 0px 23px 52px, rgba(0,0,0,0.04) 0px 14px 28px, rgba(0,0,0,0.02) 0px 7px 15px, rgba(0,0,0,0.02) 0px 3px 7px, rgba(0,0,0,0.01) 0px 1px 3px;
|
||||
|
||||
/* === Motion / Animation === */
|
||||
--duration-fast: 100ms;
|
||||
--duration-normal: 200ms;
|
||||
--duration-moderate: 300ms;
|
||||
--duration-slow: 350ms;
|
||||
--ease-default: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
--ease-in: cubic-bezier(0.4, 0, 1, 1);
|
||||
--ease-out: cubic-bezier(0, 0, 0.2, 1);
|
||||
--ease-spring: cubic-bezier(0.34, 1.56, 0.64, 1);
|
||||
|
||||
/* === Sidebar === */
|
||||
--sidebar: #f6f5f4;
|
||||
--sidebar-foreground: rgba(0,0,0,0.95);
|
||||
--sidebar-primary: #FF4D53;
|
||||
--sidebar-primary-foreground: #ffffff;
|
||||
--sidebar-accent: #e8e5e1;
|
||||
--sidebar-accent-foreground: #31302e;
|
||||
--sidebar-border: rgba(0,0,0,0.1);
|
||||
--sidebar-ring: #FF4D53;
|
||||
}
|
||||
|
||||
.dark {
|
||||
/* === Background & Surface (brightness order: page < card < subtle) === */
|
||||
--background: #191919;
|
||||
--foreground: #e0dfde;
|
||||
--card: #252422;
|
||||
--card-foreground: #e0dfde;
|
||||
--popover: #2c2b29;
|
||||
--popover-foreground: #e0dfde;
|
||||
|
||||
/* === Text Hierarchy (dark) === */
|
||||
--text-primary: #e0dfde;
|
||||
--text-secondary: #a39e98;
|
||||
--text-tertiary: #7a7672;
|
||||
--text-disabled: #555250;
|
||||
--icon-default: #a39e98;
|
||||
|
||||
/* === Surface (dark) === */
|
||||
--surface-page: #191919;
|
||||
--surface-subtle: #252422;
|
||||
--surface-muted: rgba(255, 255, 255, 0.08);
|
||||
--brand-tint: rgba(255, 141, 135, 0.16);
|
||||
--alert-badge: #ff8c4c;
|
||||
|
||||
/* === Key Color & Status (brightened for dark mode) === */
|
||||
--brand: #FF8D87; /* oklch(0.80 0.17 24) — coral lightened for dark bg */
|
||||
--primary: #e0dfde;
|
||||
--primary-foreground: #191919;
|
||||
--secondary: #252422;
|
||||
--secondary-foreground: #e0dfde;
|
||||
--muted: #252422;
|
||||
--muted-foreground: #7a7672;
|
||||
--accent: #252422;
|
||||
--accent-foreground: #e0dfde;
|
||||
--destructive: #ff8c4c;
|
||||
--destructive-foreground: #191919;
|
||||
--success: #4ec9c5;
|
||||
--success-foreground: #191919;
|
||||
--warning: #ffb347;
|
||||
--warning-foreground: #191919;
|
||||
--info: #62aef0;
|
||||
--info-foreground: #191919;
|
||||
|
||||
/* === Border & Input === */
|
||||
--border: rgba(255, 255, 255, 0.1);
|
||||
--input: rgba(255, 255, 255, 0.1);
|
||||
--input-background: #252422;
|
||||
--switch-background: #444240;
|
||||
--ring: #FF8D87;
|
||||
|
||||
/* === Shadow → replaced by borders in dark mode === */
|
||||
--shadow-card: none;
|
||||
--shadow-button: none;
|
||||
--shadow-card-hover: none;
|
||||
|
||||
--font-weight-medium: 500;
|
||||
--font-weight-normal: 400;
|
||||
--chart-1: #FF8D87;
|
||||
--chart-2: #4ec9c5;
|
||||
--chart-3: #ff8cc8;
|
||||
--chart-4: #ff8c4c;
|
||||
--chart-5: #7b8adb;
|
||||
--sidebar: #252422;
|
||||
--sidebar-foreground: #e0dfde;
|
||||
--sidebar-primary: #FF8D87;
|
||||
--sidebar-primary-foreground: #191919;
|
||||
--sidebar-accent: #2c2b29;
|
||||
--sidebar-accent-foreground: #e0dfde;
|
||||
--sidebar-border: rgba(255, 255, 255, 0.1);
|
||||
--sidebar-ring: #FF8D87;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
/* status chip backgrounds (soft tint, auto-adapts to dark via color-mix) */
|
||||
--color-success-tint: color-mix(in srgb, var(--success) 14%, var(--card));
|
||||
--color-warning-tint: color-mix(in srgb, var(--warning) 14%, var(--card));
|
||||
--color-destructive-tint: color-mix(in srgb, var(--destructive) 14%, var(--card));
|
||||
--color-info-tint: color-mix(in srgb, var(--info) 14%, var(--card));
|
||||
--color-brand: var(--brand);
|
||||
--color-success: var(--success);
|
||||
--color-success-foreground: var(--success-foreground);
|
||||
--color-warning: var(--warning);
|
||||
--color-warning-foreground: var(--warning-foreground);
|
||||
--color-info: var(--info);
|
||||
--color-info-foreground: var(--info-foreground);
|
||||
--color-text-primary: var(--text-primary);
|
||||
--color-text-secondary: var(--text-secondary);
|
||||
--color-text-tertiary: var(--text-tertiary);
|
||||
--color-text-disabled: var(--text-disabled);
|
||||
--color-icon-default: var(--icon-default);
|
||||
--color-surface-page: var(--surface-page);
|
||||
--color-surface-subtle: var(--surface-subtle);
|
||||
--color-surface-muted: var(--surface-muted);
|
||||
--color-brand-tint: var(--brand-tint);
|
||||
--color-alert-badge: var(--alert-badge);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-input-background: var(--input-background);
|
||||
--color-switch-background: var(--switch-background);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* StyleSeed — Custom SVG Icon Library
|
||||
* Standalone icon set usable without Lucide.
|
||||
* All icons: 24x24 viewBox, stroke-based, currentColor inheritance.
|
||||
*/
|
||||
|
||||
export interface IconProps {
|
||||
size?: number | string
|
||||
color?: string
|
||||
className?: string
|
||||
strokeWidth?: number
|
||||
}
|
||||
|
||||
const defaultProps = { size: 24, color: "currentColor", strokeWidth: 2 }
|
||||
|
||||
// ── Arrow ──────────────────────────────────────
|
||||
export function ArrowRight({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M9 5l7 7-7 7" /></svg>
|
||||
}
|
||||
export function ArrowLeft({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M15 19l-7-7 7-7" /></svg>
|
||||
}
|
||||
export function ArrowUp({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M5 15l7-7 7 7" /></svg>
|
||||
}
|
||||
export function ArrowDown({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M19 9l-7 7-7-7" /></svg>
|
||||
}
|
||||
|
||||
// ── Navigation ──────────────────────────────────
|
||||
export function Home({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" /></svg>
|
||||
}
|
||||
export function Search({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" /></svg>
|
||||
}
|
||||
export function User({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" /></svg>
|
||||
}
|
||||
export function Bell({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" /></svg>
|
||||
}
|
||||
export function Settings({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.573-1.066z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /></svg>
|
||||
}
|
||||
export function Menu({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M4 6h16M4 12h16M4 18h16" /></svg>
|
||||
}
|
||||
|
||||
// ── Action ──────────────────────────────────────
|
||||
export function Close({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M6 18L18 6M6 6l12 12" /></svg>
|
||||
}
|
||||
export function Check({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M5 13l4 4L19 7" /></svg>
|
||||
}
|
||||
export function Plus({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M12 4v16m8-8H4" /></svg>
|
||||
}
|
||||
export function Minus({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M20 12H4" /></svg>
|
||||
}
|
||||
export function MoreVertical({ size = defaultProps.size, color = defaultProps.color, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill={color} className={className}><circle cx="12" cy="5" r="1.5" /><circle cx="12" cy="12" r="1.5" /><circle cx="12" cy="19" r="1.5" /></svg>
|
||||
}
|
||||
|
||||
// ── Status ──────────────────────────────────────
|
||||
export function Info({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
|
||||
}
|
||||
export function AlertCircle({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
|
||||
}
|
||||
export function AlertTriangle({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" /></svg>
|
||||
}
|
||||
export function CheckCircle({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
|
||||
}
|
||||
|
||||
// ── File & Data ──────────────────────────────────
|
||||
export function Upload({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" /></svg>
|
||||
}
|
||||
export function Download({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg>
|
||||
}
|
||||
export function Calendar({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
|
||||
}
|
||||
export function Document({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
|
||||
}
|
||||
|
||||
// ── Visibility ──────────────────────────────────
|
||||
export function EyeOpen({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" /></svg>
|
||||
}
|
||||
export function EyeClosed({ size = defaultProps.size, color = defaultProps.color, strokeWidth = defaultProps.strokeWidth, className }: IconProps) {
|
||||
return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} className={className}><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={strokeWidth} d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" /></svg>
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
:root {
|
||||
--accent: #4cc9a7;
|
||||
--background: #0d1110;
|
||||
--border: #2d3834;
|
||||
--border-strong: #46554f;
|
||||
--danger: #d86666;
|
||||
--danger-strong: #f2a3a3;
|
||||
--surface: #151a18;
|
||||
--surface-soft: #1c2420;
|
||||
--text: #d9e1dc;
|
||||
--text-muted: #a6b1ab;
|
||||
--text-strong: #f4f7f5;
|
||||
--text-subtle: #808b85;
|
||||
--warning: #d4a944;
|
||||
--warning-strong: #efd18a;
|
||||
|
||||
color: var(--text);
|
||||
background: var(--background);
|
||||
font: 16px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
|
||||
'Segoe UI', sans-serif;
|
||||
font-synthesis: none;
|
||||
letter-spacing: 0;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
min-width: 320px;
|
||||
min-height: 100svh;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
button,
|
||||
input {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button,
|
||||
a {
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
a:focus-visible,
|
||||
input:focus-visible {
|
||||
outline: 3px solid color-mix(in srgb, var(--accent) 42%, transparent);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3,
|
||||
p {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
h1,
|
||||
h2,
|
||||
h3 {
|
||||
margin: 0;
|
||||
color: var(--text-strong);
|
||||
font-weight: 800;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
h1 {
|
||||
max-width: 860px;
|
||||
font-size: 56px;
|
||||
line-height: 1.02;
|
||||
}
|
||||
|
||||
h2 {
|
||||
font-size: 20px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
img,
|
||||
svg {
|
||||
display: block;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: color-mix(in srgb, var(--accent) 38%, transparent);
|
||||
color: var(--text-strong);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
h1 {
|
||||
font-size: 34px;
|
||||
line-height: 1.08;
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import type { AnalysisPlatformRoute, AnalysisRequestDto } from '@persona-lenz/shared';
|
||||
|
||||
const CACHE_PREFIX = 'persona-lenz:analysis-request:';
|
||||
|
||||
export function saveAnalysisRequest(
|
||||
jobId: string,
|
||||
request: AnalysisRequestDto,
|
||||
): void {
|
||||
try {
|
||||
window.sessionStorage.setItem(
|
||||
getCacheKey(jobId),
|
||||
JSON.stringify({
|
||||
gameName: request.gameName,
|
||||
matchCount: request.matchCount,
|
||||
platform: request.platform,
|
||||
tagLine: request.tagLine,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Retry is a convenience path; analysis itself should not depend on storage.
|
||||
}
|
||||
}
|
||||
|
||||
export function loadAnalysisRequest(jobId: string): AnalysisRequestDto | null {
|
||||
try {
|
||||
const rawRequest = window.sessionStorage.getItem(getCacheKey(jobId));
|
||||
|
||||
if (!rawRequest) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsedRequest = JSON.parse(rawRequest) as Partial<AnalysisRequestDto>;
|
||||
|
||||
if (
|
||||
typeof parsedRequest.gameName === 'string' &&
|
||||
typeof parsedRequest.tagLine === 'string'
|
||||
) {
|
||||
return {
|
||||
gameName: parsedRequest.gameName,
|
||||
matchCount:
|
||||
typeof parsedRequest.matchCount === 'number'
|
||||
? parsedRequest.matchCount
|
||||
: undefined,
|
||||
platform:
|
||||
typeof parsedRequest.platform === 'string'
|
||||
? (parsedRequest.platform as AnalysisPlatformRoute)
|
||||
: undefined,
|
||||
tagLine: parsedRequest.tagLine,
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
clearAnalysisRequest(jobId);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function clearAnalysisRequest(jobId: string): void {
|
||||
try {
|
||||
window.sessionStorage.removeItem(getCacheKey(jobId));
|
||||
} catch {
|
||||
// Ignore storage failures.
|
||||
}
|
||||
}
|
||||
|
||||
function getCacheKey(jobId: string): string {
|
||||
return `${CACHE_PREFIX}${jobId}`;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type {
|
||||
AnalysisJobStatusDto,
|
||||
AnalysisRequestAcceptedDto,
|
||||
AnalysisRequestDto,
|
||||
PlayerAnalysisDto,
|
||||
SimilarPlayersDto,
|
||||
} from '@persona-lenz/shared'
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number
|
||||
|
||||
constructor(status: number, message: string) {
|
||||
super(message)
|
||||
this.name = 'ApiError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(path, init)
|
||||
} catch {
|
||||
throw new ApiError(0, '서버에 연결하지 못했어요. 네트워크를 확인하고 다시 시도해 주세요.')
|
||||
}
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { message?: string | string[] } | null
|
||||
const message = Array.isArray(body?.message) ? body.message[0] : body?.message
|
||||
throw new ApiError(response.status, message ?? `요청에 실패했어요. (${response.status})`)
|
||||
}
|
||||
return (await response.json()) as T
|
||||
}
|
||||
|
||||
export function requestAnalysis(payload: AnalysisRequestDto): Promise<AnalysisRequestAcceptedDto> {
|
||||
return request('/api/analysis/request', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
}
|
||||
|
||||
export function getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
|
||||
return request(`/api/analysis/jobs/${encodeURIComponent(jobId)}`)
|
||||
}
|
||||
|
||||
export function getLatestAnalysis(puuid: string): Promise<PlayerAnalysisDto> {
|
||||
return request(`/api/players/${encodeURIComponent(puuid)}/analysis/latest`)
|
||||
}
|
||||
|
||||
export function getSimilarPlayers(puuid: string): Promise<SimilarPlayersDto> {
|
||||
return request(`/api/players/${encodeURIComponent(puuid)}/similar-players`)
|
||||
}
|
||||
|
||||
const LAST_REQUEST_KEY = 'pl:last-analysis-request'
|
||||
|
||||
export function saveLastRequest(payload: AnalysisRequestDto): void {
|
||||
try {
|
||||
sessionStorage.setItem(LAST_REQUEST_KEY, JSON.stringify(payload))
|
||||
} catch {
|
||||
// storage 불가 환경에서도 분석 자체는 계속 진행
|
||||
}
|
||||
}
|
||||
|
||||
export function loadLastRequest(): AnalysisRequestDto | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(LAST_REQUEST_KEY)
|
||||
if (!raw) return null
|
||||
const parsed = JSON.parse(raw) as AnalysisRequestDto
|
||||
if (!parsed.gameName || !parsed.tagLine) return null
|
||||
return parsed
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import * as React from 'react'
|
||||
|
||||
const CDN = 'https://ddragon.leagueoflegends.com'
|
||||
const CACHE_KEY = 'pl:ddragon:champions:v1'
|
||||
|
||||
export interface ChampionInfo {
|
||||
/** Data Dragon 이미지 경로용 슬러그. 예: 'Ahri' */
|
||||
slug: string
|
||||
/** 한국어 이름. 예: '아리' */
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ChampionIndex {
|
||||
version: string
|
||||
byId: ReadonlyMap<number, ChampionInfo>
|
||||
}
|
||||
|
||||
interface CachePayload {
|
||||
version: string
|
||||
entries: [number, ChampionInfo][]
|
||||
}
|
||||
|
||||
function readCache(): ChampionIndex | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(CACHE_KEY)
|
||||
if (!raw) return null
|
||||
const parsed = JSON.parse(raw) as CachePayload
|
||||
if (!parsed.version || !Array.isArray(parsed.entries)) return null
|
||||
return { version: parsed.version, byId: new Map(parsed.entries) }
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(index: ChampionIndex): void {
|
||||
try {
|
||||
const payload: CachePayload = { version: index.version, entries: [...index.byId.entries()] }
|
||||
localStorage.setItem(CACHE_KEY, JSON.stringify(payload))
|
||||
} catch {
|
||||
// 캐시는 best-effort — 실패해도 CDN 조회는 계속 동작
|
||||
}
|
||||
}
|
||||
|
||||
let inflight: Promise<ChampionIndex> | null = null
|
||||
|
||||
async function fetchChampionIndex(): Promise<ChampionIndex> {
|
||||
const versions = (await (await fetch(`${CDN}/api/versions.json`)).json()) as string[]
|
||||
const version = versions[0]
|
||||
const cached = readCache()
|
||||
if (cached && cached.version === version) return cached
|
||||
|
||||
const championData = (await (
|
||||
await fetch(`${CDN}/cdn/${version}/data/ko_KR/champion.json`)
|
||||
).json()) as { data: Record<string, { key: string; id: string; name: string }> }
|
||||
|
||||
const byId = new Map<number, ChampionInfo>()
|
||||
for (const champion of Object.values(championData.data)) {
|
||||
byId.set(Number(champion.key), { slug: champion.id, name: champion.name })
|
||||
}
|
||||
const index: ChampionIndex = { version, byId }
|
||||
writeCache(index)
|
||||
return index
|
||||
}
|
||||
|
||||
export function getChampionIndex(): Promise<ChampionIndex> {
|
||||
inflight ??= fetchChampionIndex().catch((cause) => {
|
||||
inflight = null
|
||||
throw cause
|
||||
})
|
||||
return inflight
|
||||
}
|
||||
|
||||
/** 챔피언 인덱스 로딩 훅. 실패 시 null 유지 — 화면은 챔피언 ID로 폴백 표기 */
|
||||
export function useChampionIndex(): ChampionIndex | null {
|
||||
const [index, setIndex] = React.useState<ChampionIndex | null>(null)
|
||||
React.useEffect(() => {
|
||||
let cancelled = false
|
||||
getChampionIndex()
|
||||
.then((loaded) => {
|
||||
if (!cancelled) setIndex(loaded)
|
||||
})
|
||||
.catch(() => {
|
||||
// 네트워크 실패 시 이름/이미지 없이 진행
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [])
|
||||
return index
|
||||
}
|
||||
|
||||
export function championImageUrl(version: string, slug: string): string {
|
||||
return `${CDN}/cdn/${version}/img/champion/${slug}.png`
|
||||
}
|
||||
|
||||
export function profileIconUrl(version: string, profileIconId: number): string {
|
||||
return `${CDN}/cdn/${version}/img/profileicon/${profileIconId}.png`
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import {
|
||||
METRICS,
|
||||
type MetricDefinition,
|
||||
type MetricId,
|
||||
type Role,
|
||||
} from '@persona-lenz/shared';
|
||||
|
||||
export const ROLE_LABELS: Record<Role, string> = {
|
||||
BOTTOM: '원딜',
|
||||
JUNGLE: '정글',
|
||||
MIDDLE: '미드',
|
||||
TOP: '탑',
|
||||
UTILITY: '서포터',
|
||||
};
|
||||
|
||||
export const STAGE_LABELS: Record<string, string> = {
|
||||
'build-profile': '플레이스타일 프로필 생성',
|
||||
completed: '분석 완료',
|
||||
enqueue: '분석 작업 등록',
|
||||
'extract-features': '매치 지표 추출',
|
||||
'fetch-match-details': '최근 랭크 게임 수집',
|
||||
'fetch-match-ids': '랭크 게임 목록 조회',
|
||||
queued: '대기열 등록',
|
||||
'resolve-account': 'Riot ID 확인',
|
||||
};
|
||||
|
||||
const metricLabelById = new Map<MetricId, string>(
|
||||
METRICS.map((metric) => [metric.id, metric.label]),
|
||||
);
|
||||
const metricDefinitionById = new Map<MetricId, MetricDefinition>(
|
||||
METRICS.map((metric) => [metric.id, metric]),
|
||||
);
|
||||
|
||||
export function formatPercent(value: number): string {
|
||||
return `${Math.round(value * 100)}%`;
|
||||
}
|
||||
|
||||
export function getMetricLabel(metricId: MetricId): string {
|
||||
return metricLabelById.get(metricId) ?? metricId;
|
||||
}
|
||||
|
||||
export function getMetricDescription(metricId: MetricId): string {
|
||||
return (
|
||||
metricDefinitionById.get(metricId)?.description ??
|
||||
'정규화된 플레이스타일 지표입니다.'
|
||||
);
|
||||
}
|
||||
|
||||
export function getMetricDirectionLabel(metricId: MetricId): string {
|
||||
const direction = metricDefinitionById.get(metricId)?.direction;
|
||||
|
||||
if (direction === 'lowerIsBetter') {
|
||||
return '낮을수록 좋음';
|
||||
}
|
||||
if (direction === 'higherIsBetter') {
|
||||
return '높을수록 좋음';
|
||||
}
|
||||
return '참고 지표';
|
||||
}
|
||||
|
||||
export function getStageLabel(stage?: string): string {
|
||||
if (!stage) {
|
||||
return '작업 상태 확인';
|
||||
}
|
||||
|
||||
return STAGE_LABELS[stage] ?? stage;
|
||||
}
|
||||
|
||||
export function formatTier({
|
||||
leaguePoints,
|
||||
losses,
|
||||
queueType,
|
||||
rank,
|
||||
tier,
|
||||
wins,
|
||||
}: {
|
||||
leaguePoints: number;
|
||||
losses: number;
|
||||
queueType: string;
|
||||
rank: string;
|
||||
tier: string;
|
||||
wins: number;
|
||||
}): string {
|
||||
const queueLabel =
|
||||
queueType === 'RANKED_SOLO_5x5' ? '솔로랭크' : queueType.replaceAll('_', ' ');
|
||||
|
||||
return `${queueLabel} ${tier} ${rank} ${leaguePoints}LP · ${wins}승 ${losses}패`;
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { METRICS, type MetricDefinition, type MetricId, type Role } from '@persona-lenz/shared'
|
||||
|
||||
export const METRIC_BY_ID: ReadonlyMap<MetricId, MetricDefinition> = new Map(
|
||||
METRICS.map((metric) => [metric.id, metric]),
|
||||
)
|
||||
|
||||
/**
|
||||
* 정규화 값(0~1)을 "높을수록 좋음"으로 통일한 0~100 점수.
|
||||
* lowerIsBetter 지표는 반전한다 — 레이더/막대/강점·약점 표시 전용.
|
||||
*/
|
||||
export function displayScore(metricId: MetricId, value: number): number {
|
||||
const metric = METRIC_BY_ID.get(metricId)
|
||||
const adjusted = metric?.direction === 'lowerIsBetter' ? 1 - value : value
|
||||
return Math.round(Math.min(Math.max(adjusted, 0), 1) * 100)
|
||||
}
|
||||
|
||||
export interface MetricCategory {
|
||||
id: string
|
||||
label: string
|
||||
metricIds: MetricId[]
|
||||
}
|
||||
|
||||
/** 39개 지표를 6개 카테고리로 묶는다. 레이더 축과 상세 탭의 단일 기준. */
|
||||
export const METRIC_CATEGORIES: MetricCategory[] = [
|
||||
{
|
||||
id: 'combat',
|
||||
label: '전투',
|
||||
metricIds: ['kda', 'killParticipation', 'damageShare', 'damagePerMin', 'soloKills', 'ccTimePerMinute'],
|
||||
},
|
||||
{
|
||||
id: 'growth',
|
||||
label: '성장·자원',
|
||||
metricIds: ['goldPerMin', 'csPerMin', 'shutdownGoldCollectedPerGame'],
|
||||
},
|
||||
{
|
||||
id: 'survival',
|
||||
label: '생존·판단',
|
||||
metricIds: [
|
||||
'deathsPerMin',
|
||||
'isolationTendency',
|
||||
'deathWithShutdownBountyGivenRate',
|
||||
'deathFollowedByTeamLossRate',
|
||||
'deathTradedForTeamAdvantageRate',
|
||||
'deathWhileIsolatedFromNearestAllyRate',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'vision',
|
||||
label: '시야',
|
||||
metricIds: [
|
||||
'visionScorePerMin',
|
||||
'wardsKilledPerMin',
|
||||
'controlWardsPlaced',
|
||||
'earlyWardsPerMin',
|
||||
'objectivePreWardRate',
|
||||
'preObjectivePitPresenceRate',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'laning',
|
||||
label: '라인전',
|
||||
metricIds: [
|
||||
'goldDiffAt10',
|
||||
'goldDiffAt14',
|
||||
'csDiffAt10',
|
||||
'xpDiffAt10',
|
||||
'deathsBefore14',
|
||||
'killParticipationBefore14',
|
||||
'earlyDeficitRecoveryRate',
|
||||
'laneLeadConversionRate',
|
||||
'platePresenceParticipationRate',
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'objective',
|
||||
label: '오브젝트·한타',
|
||||
metricIds: [
|
||||
'objectiveParticipation',
|
||||
'eliteObjectiveParticipationRate',
|
||||
'teamfightFirstEngagementParticipationRate',
|
||||
'teamfightCleanupKillParticipationRate',
|
||||
'objectiveFightOpeningParticipationRate',
|
||||
'objectiveFightOpeningConvertedToObjectiveRate',
|
||||
'preObjectivePickParticipationRate',
|
||||
'roamConvertedToTeamAdvantageRate',
|
||||
'objectiveBountyComebackParticipationRate',
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
export interface CategoryScore {
|
||||
category: MetricCategory
|
||||
/** 카테고리 내 존재하는 지표 displayScore 평균 (0~100). 지표가 없으면 null */
|
||||
score: number | null
|
||||
}
|
||||
|
||||
export function computeCategoryScores(playstyle: Partial<Record<MetricId, number>>): CategoryScore[] {
|
||||
return METRIC_CATEGORIES.map((category) => {
|
||||
const scores = category.metricIds
|
||||
.filter((metricId) => playstyle[metricId] != null)
|
||||
.map((metricId) => displayScore(metricId, playstyle[metricId]!))
|
||||
return {
|
||||
category,
|
||||
score: scores.length > 0 ? Math.round(scores.reduce((sum, s) => sum + s, 0) / scores.length) : null,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const ROLE_LABELS: Record<Role | 'UNKNOWN', string> = {
|
||||
TOP: '탑',
|
||||
JUNGLE: '정글',
|
||||
MIDDLE: '미드',
|
||||
BOTTOM: '원딜',
|
||||
UTILITY: '서포터',
|
||||
UNKNOWN: '역할 불명',
|
||||
}
|
||||
|
||||
const TIER_LABELS: Record<string, string> = {
|
||||
IRON: '아이언',
|
||||
BRONZE: '브론즈',
|
||||
SILVER: '실버',
|
||||
GOLD: '골드',
|
||||
PLATINUM: '플래티넘',
|
||||
EMERALD: '에메랄드',
|
||||
DIAMOND: '다이아몬드',
|
||||
MASTER: '마스터',
|
||||
GRANDMASTER: '그랜드마스터',
|
||||
CHALLENGER: '챌린저',
|
||||
}
|
||||
|
||||
const APEX_TIERS = new Set(['MASTER', 'GRANDMASTER', 'CHALLENGER'])
|
||||
|
||||
export function formatTier(tier?: string, division?: string): string | null {
|
||||
if (!tier) return null
|
||||
const label = TIER_LABELS[tier] ?? tier
|
||||
if (!division || APEX_TIERS.has(tier)) return label
|
||||
return `${label} ${division}`
|
||||
}
|
||||
+12
-3
@@ -1,10 +1,19 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './app/App'
|
||||
import './css/index.css'
|
||||
|
||||
// Notion 스킨의 .dark 팔레트를 시스템 다크 모드와 동기화
|
||||
const media = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
const syncTheme = () => document.documentElement.classList.toggle('dark', media.matches)
|
||||
syncTheme()
|
||||
media.addEventListener('change', syncTheme)
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* Motion seed types — five named animation feels, each with five reusable contexts.
|
||||
*
|
||||
* A seed is a complete personality (Spring, Silk, Snap, Float, Pulse).
|
||||
* A context is where that personality lands: entrance, exit, hover, press, layout.
|
||||
* Each context returns props you can spread directly onto a `<motion.X>` — and
|
||||
* multiple contexts compose because every transition is embedded inside its
|
||||
* own state object (animate / exit / whileHover / whileTap) rather than
|
||||
* sitting at the top level where it would collide.
|
||||
*
|
||||
* Example:
|
||||
* <motion.button {...spring.hover} {...spring.press}>Save</motion.button>
|
||||
* <AnimatePresence>
|
||||
* {open && <motion.div {...silk.entrance} {...silk.exit} />}
|
||||
* </AnimatePresence>
|
||||
*/
|
||||
|
||||
import type { MotionProps } from "framer-motion";
|
||||
|
||||
/** The five contexts every seed defines. */
|
||||
export type SeedContext = "entrance" | "exit" | "hover" | "press" | "layout";
|
||||
|
||||
/** Shape spread onto a `<motion.X>` for an entrance animation. */
|
||||
export type EntranceRecipe = Required<Pick<MotionProps, "initial" | "animate">>;
|
||||
|
||||
/** Shape for an exit animation. Pair with `<AnimatePresence>`. */
|
||||
export type ExitRecipe = Required<Pick<MotionProps, "exit">>;
|
||||
|
||||
/** Shape for a hover interaction. */
|
||||
export type HoverRecipe = Required<Pick<MotionProps, "whileHover">>;
|
||||
|
||||
/** Shape for a tap/press interaction. */
|
||||
export type PressRecipe = Required<Pick<MotionProps, "whileTap">>;
|
||||
|
||||
/** Shape for FLIP-style layout animations. Layout transition stays top-level
|
||||
* because framer-motion only reads it there. */
|
||||
export type LayoutRecipe = Required<Pick<MotionProps, "layout" | "transition">>;
|
||||
|
||||
/** A complete seed: one personality across all five contexts. */
|
||||
export type SeedConfig = {
|
||||
/** The seed name as it appears in vocab/docs. */
|
||||
readonly name: string;
|
||||
/** One-line vibe description for the LLM and UI. */
|
||||
readonly vibe: string;
|
||||
readonly entrance: EntranceRecipe;
|
||||
readonly exit: ExitRecipe;
|
||||
readonly hover: HoverRecipe;
|
||||
readonly press: PressRecipe;
|
||||
readonly layout: LayoutRecipe;
|
||||
};
|
||||
|
||||
/** Convenience: pull every recipe for a single seed. */
|
||||
export type SeedRecipes = Pick<SeedConfig, SeedContext>;
|
||||
@@ -0,0 +1,100 @@
|
||||
/**
|
||||
* @styleseed/motion — five named animation seeds for AI-assisted UI work.
|
||||
*
|
||||
* Spread a recipe onto any `<motion.X>` to apply that seed in one of five
|
||||
* standard contexts: entrance, exit, hover, press, layout.
|
||||
*
|
||||
* import { spring, silk } from "@styleseed/motion"
|
||||
*
|
||||
* <motion.button {...spring.hover} {...spring.press}>Save</motion.button>
|
||||
* <motion.div {...silk.entrance} {...silk.exit} layout {...silk.layout}>
|
||||
*
|
||||
* See README.md for vibe vocabulary and brand→seed default mapping.
|
||||
*/
|
||||
|
||||
import { spring } from "./seeds/spring";
|
||||
import { silk } from "./seeds/silk";
|
||||
import { snap } from "./seeds/snap";
|
||||
import { float } from "./seeds/float";
|
||||
import { pulse } from "./seeds/pulse";
|
||||
|
||||
export { spring, silk, snap, float, pulse };
|
||||
/** REDUCED_TRANSITION is data, safe in any context. */
|
||||
export { REDUCED_TRANSITION } from "./reduced-motion";
|
||||
/** Named, copy-pasteable motion keyword library (shared by /motion + /ss-motion). */
|
||||
export {
|
||||
MOTION_LIBRARY,
|
||||
MOTION_BY_KEY,
|
||||
MOTION_CATEGORIES,
|
||||
MOTION_BY_USECASE,
|
||||
type MotionKeyword,
|
||||
type MotionCategory,
|
||||
type MotionUseCase,
|
||||
} from "./library";
|
||||
// usePrefersReducedMotion is a React hook — import directly from
|
||||
// "@engine/motion/reduced-motion" inside a "use client" file to keep
|
||||
// this barrel safe to import from Server Components.
|
||||
export type {
|
||||
SeedContext,
|
||||
SeedConfig,
|
||||
SeedRecipes,
|
||||
EntranceRecipe,
|
||||
ExitRecipe,
|
||||
HoverRecipe,
|
||||
PressRecipe,
|
||||
LayoutRecipe,
|
||||
} from "./contexts";
|
||||
|
||||
/** All seeds keyed by name. Useful for iteration in showcase pages. */
|
||||
export const seeds = { spring, silk, snap, float, pulse } as const;
|
||||
|
||||
/** Discriminated union of seed ids. */
|
||||
export type SeedId = keyof typeof seeds;
|
||||
|
||||
/** Brand → recommended default seed. Users may override per page or per element. */
|
||||
export const BRAND_DEFAULT_SEED: Record<string, SeedId> = {
|
||||
toss: "spring",
|
||||
stripe: "silk",
|
||||
linear: "snap",
|
||||
raycast: "snap",
|
||||
arc: "spring",
|
||||
notion: "silk",
|
||||
vercel: "snap",
|
||||
};
|
||||
|
||||
/** Vibe word → seed lookup. Used by /ss-motion to translate prompts. */
|
||||
export const VIBE_TO_SEED: Record<string, SeedId> = {
|
||||
// Spring
|
||||
bouncy: "spring",
|
||||
springy: "spring",
|
||||
playful: "spring",
|
||||
energetic: "spring",
|
||||
alive: "spring",
|
||||
// Silk
|
||||
smooth: "silk",
|
||||
silky: "silk",
|
||||
fluid: "silk",
|
||||
elegant: "silk",
|
||||
composed: "silk",
|
||||
continuous: "silk",
|
||||
// Snap
|
||||
snappy: "snap",
|
||||
quick: "snap",
|
||||
instant: "snap",
|
||||
decisive: "snap",
|
||||
sharp: "snap",
|
||||
precise: "snap",
|
||||
// Float
|
||||
floaty: "float",
|
||||
gentle: "float",
|
||||
weightless: "float",
|
||||
dreamy: "float",
|
||||
ambient: "float",
|
||||
drifting: "float",
|
||||
// Pulse
|
||||
rhythmic: "pulse",
|
||||
punchy: "pulse",
|
||||
pulsing: "pulse",
|
||||
heartbeat: "pulse",
|
||||
beat: "pulse",
|
||||
};
|
||||
@@ -0,0 +1,473 @@
|
||||
import type { SeedId } from "./index";
|
||||
|
||||
/**
|
||||
* Motion Keyword Library — the named, copy-pasteable motion vocabulary.
|
||||
*
|
||||
* This is the SINGLE SOURCE OF TRUTH shared by two surfaces:
|
||||
* 1. the `/motion` gallery (live demo + Copy button per keyword)
|
||||
* 2. the `/ss-motion` skill (keyword → code lookup for vibe coding)
|
||||
*
|
||||
* The 5 seeds (spring/silk/snap/float/pulse) define a *personality*.
|
||||
* These keywords define a *distinctive move* — a flip, a curtain wipe,
|
||||
* a morph — so "make the toggle flip" maps to exactly one recipe and
|
||||
* every page in the repo gets the same motion. That keyword↔code
|
||||
* contract is the thing a plain UI-template gallery can't offer.
|
||||
*
|
||||
* Each entry is pure data (safe to import from a Server Component).
|
||||
* The live demo JSX lives in the gallery page, keyed by `key`.
|
||||
*/
|
||||
|
||||
export type MotionCategory =
|
||||
| "flair"
|
||||
| "toggle"
|
||||
| "reveal"
|
||||
| "press"
|
||||
| "attention"
|
||||
| "list";
|
||||
|
||||
export interface MotionKeyword {
|
||||
/** Unique handle — what you type when vibe coding. e.g. "toggle-flip". */
|
||||
key: string;
|
||||
/** Short human label for the gallery card. */
|
||||
label: string;
|
||||
category: MotionCategory;
|
||||
/** One-line description of the move. */
|
||||
vibe: string;
|
||||
/** Closest personality seed, for consistency guidance. */
|
||||
seed: SeedId;
|
||||
/** Copy-pasteable, runnable framer-motion snippet. */
|
||||
snippet: string;
|
||||
}
|
||||
|
||||
export const MOTION_CATEGORIES: { id: MotionCategory; label: string; blurb: string }[] = [
|
||||
{ id: "flair", label: "Flair", blurb: "Showy, cursor-aware, scroll-stopping moves." },
|
||||
{ id: "toggle", label: "Toggle", blurb: "One control, many ways to switch state." },
|
||||
{ id: "reveal", label: "Reveal", blurb: "How an element arrives on screen." },
|
||||
{ id: "press", label: "Press", blurb: "Tactile feedback on tap/click." },
|
||||
{ id: "attention", label: "Attention", blurb: "Looping or one-shot focus pulls." },
|
||||
{ id: "list", label: "List", blurb: "Choreography across many items." },
|
||||
];
|
||||
|
||||
/**
|
||||
* Motion by use-case — a LIGHT rule, not a mandate. Maps a common UI moment to
|
||||
* the seed or keyword that fits, with the one-line reason. Powers the "which
|
||||
* motion when" cheat on /motion and the recommend mode in /ss-motion.
|
||||
*
|
||||
* Two anti-rules override everything below:
|
||||
* 1. ONE seed per product — pick a personality and keep it; mixing reads as sloppy.
|
||||
* 2. NEVER delay content the user came for — don't animate a balance, a search
|
||||
* result, or a price into view. Motion is for affordance, not for the payload.
|
||||
*/
|
||||
export interface MotionUseCase {
|
||||
/** the UI moment */
|
||||
useCase: string;
|
||||
/** recommended seed id or keyword handle */
|
||||
recommend: string;
|
||||
/** one-line why */
|
||||
why: string;
|
||||
}
|
||||
|
||||
export const MOTION_BY_USECASE: MotionUseCase[] = [
|
||||
{ useCase: "Primary button / CTA press", recommend: "spring · press", why: "Tactile, confident feedback — the press should feel like it 'gives'." },
|
||||
{ useCase: "Modal / dialog / bottom sheet enter", recommend: "silk · entrance", why: "Smooth and composed; never bounce serious or destructive content in." },
|
||||
{ useCase: "Dropdown / popover / menu", recommend: "snap · entrance", why: "Instant and precise — frequent UI shouldn't make you wait." },
|
||||
{ useCase: "Toast / inline notification", recommend: "spring · entrance", why: "A small friendly arrival that catches the eye without blocking." },
|
||||
{ useCase: "List / feed items appearing", recommend: "stagger-cascade", why: "Choreograph many items so the eye follows the order, gently." },
|
||||
{ useCase: "Feature / marketing card hover", recommend: "tilt-3d", why: "Depth and flair are welcome on content-light marketing surfaces." },
|
||||
{ useCase: "Dashboard / data card hover", recommend: "snap · hover", why: "A subtle lift only — restraint keeps a dense data UI calm." },
|
||||
{ useCase: "Like / favorite / reaction", recommend: "like-burst", why: "A celebratory one-shot; reward the tap." },
|
||||
{ useCase: "Live / online / recording dot", recommend: "pulse-beat", why: "A looping heartbeat signals 'alive' without stealing focus." },
|
||||
{ useCase: "Loading / skeleton", recommend: "shimmer", why: "Calm, directional progress — communicates work without anxiety." },
|
||||
{ useCase: "Success / confirmation", recommend: "pop-in", why: "A positive little arrival that says 'done'." },
|
||||
{ useCase: "Toggle / tab / segment switch", recommend: "toggle-flip", why: "A distinctive, recognizable switch tied to one handle." },
|
||||
{ useCase: "Page / route transition", recommend: "silk · entrance", why: "Smooth and minimal; get out of the way fast." },
|
||||
{ useCase: "Number / balance / KPI / price reveal", recommend: "none", why: "Don't animate the payload — the user came to read it instantly." },
|
||||
];
|
||||
|
||||
export const MOTION_LIBRARY: MotionKeyword[] = [
|
||||
// ── Flair (showy, cursor/scroll-aware) ───────────────────
|
||||
{
|
||||
key: "tilt-3d",
|
||||
label: "3D tilt",
|
||||
category: "flair",
|
||||
vibe: "Card tilts in 3D toward the cursor — depth on hover",
|
||||
seed: "silk",
|
||||
snippet: `import { motion, useMotionValue, useSpring, useTransform } from "framer-motion";
|
||||
|
||||
const x = useMotionValue(0);
|
||||
const y = useMotionValue(0);
|
||||
const rotateX = useSpring(useTransform(y, [-0.5, 0.5], [12, -12]), { stiffness: 250, damping: 20 });
|
||||
const rotateY = useSpring(useTransform(x, [-0.5, 0.5], [-12, 12]), { stiffness: 250, damping: 20 });
|
||||
|
||||
<motion.div
|
||||
onPointerMove={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
x.set((e.clientX - r.left) / r.width - 0.5);
|
||||
y.set((e.clientY - r.top) / r.height - 0.5);
|
||||
}}
|
||||
onPointerLeave={() => { x.set(0); y.set(0); }}
|
||||
style={{ rotateX, rotateY, transformPerspective: 800 }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "magnetic",
|
||||
label: "Magnetic",
|
||||
category: "flair",
|
||||
vibe: "Button drifts toward the cursor, springs back on leave",
|
||||
seed: "spring",
|
||||
snippet: `import { motion, useSpring } from "framer-motion";
|
||||
|
||||
const x = useSpring(0, { stiffness: 300, damping: 20 });
|
||||
const y = useSpring(0, { stiffness: 300, damping: 20 });
|
||||
|
||||
<motion.button
|
||||
onPointerMove={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
x.set((e.clientX - r.left - r.width / 2) * 0.4);
|
||||
y.set((e.clientY - r.top - r.height / 2) * 0.4);
|
||||
}}
|
||||
onPointerLeave={() => { x.set(0); y.set(0); }}
|
||||
style={{ x, y }}
|
||||
>
|
||||
Hover me
|
||||
</motion.button>`,
|
||||
},
|
||||
{
|
||||
key: "glow-pulse",
|
||||
label: "Glow pulse",
|
||||
category: "flair",
|
||||
vibe: "Breathing neon glow — draws the eye to a hot CTA",
|
||||
seed: "pulse",
|
||||
snippet: `<motion.div
|
||||
animate={{
|
||||
boxShadow: [
|
||||
"0 0 0px rgba(99,91,255,0)",
|
||||
"0 0 28px rgba(99,91,255,0.7)",
|
||||
"0 0 0px rgba(99,91,255,0)",
|
||||
],
|
||||
}}
|
||||
transition={{ duration: 1.8, repeat: Infinity, ease: "easeInOut" }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "gradient-sweep",
|
||||
label: "Gradient sweep",
|
||||
category: "flair",
|
||||
vibe: "Animated gradient flows through text or a surface",
|
||||
seed: "silk",
|
||||
snippet: `<motion.span
|
||||
animate={{ backgroundPosition: ["0% 50%", "100% 50%"] }}
|
||||
transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
|
||||
style={{
|
||||
backgroundImage: "linear-gradient(90deg,#6C5CE7,#FF6B6B,#FFD93D,#6C5CE7)",
|
||||
backgroundSize: "300% 100%",
|
||||
WebkitBackgroundClip: "text",
|
||||
WebkitTextFillColor: "transparent",
|
||||
}}
|
||||
>
|
||||
Gradient
|
||||
</motion.span>`,
|
||||
},
|
||||
{
|
||||
key: "blob-morph",
|
||||
label: "Blob morph",
|
||||
category: "flair",
|
||||
vibe: "Organic shape endlessly morphs — living background blob",
|
||||
seed: "float",
|
||||
snippet: `<motion.div
|
||||
animate={{
|
||||
borderRadius: [
|
||||
"60% 40% 30% 70% / 60% 30% 70% 40%",
|
||||
"30% 60% 70% 40% / 50% 60% 30% 60%",
|
||||
"60% 40% 30% 70% / 60% 30% 70% 40%",
|
||||
],
|
||||
}}
|
||||
transition={{ duration: 8, repeat: Infinity, ease: "easeInOut" }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "spotlight",
|
||||
label: "Spotlight",
|
||||
category: "flair",
|
||||
vibe: "Radial light follows the cursor across a card",
|
||||
seed: "silk",
|
||||
snippet: `import { motion, useMotionValue, useMotionTemplate } from "framer-motion";
|
||||
|
||||
const mx = useMotionValue(50);
|
||||
const my = useMotionValue(50);
|
||||
const bg = useMotionTemplate\`radial-gradient(160px circle at \${mx}% \${my}%, rgba(255,255,255,0.25), transparent 60%)\`;
|
||||
|
||||
<motion.div
|
||||
onPointerMove={(e) => {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
mx.set(((e.clientX - r.left) / r.width) * 100);
|
||||
my.set(((e.clientY - r.top) / r.height) * 100);
|
||||
}}
|
||||
style={{ backgroundImage: bg }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "text-scramble",
|
||||
label: "Scramble",
|
||||
category: "flair",
|
||||
vibe: "Letters decode into place — hacker/terminal reveal",
|
||||
seed: "snap",
|
||||
snippet: `const CHARS = "!<>-_\\\\/[]{}—=+*^?#";
|
||||
const [text, setText] = useState("StyleSeed");
|
||||
|
||||
function scramble(target: string) {
|
||||
let frame = 0;
|
||||
const id = setInterval(() => {
|
||||
setText(
|
||||
target
|
||||
.split("")
|
||||
.map((c, i) => (i < frame / 3 ? c : CHARS[Math.floor(Math.random() * CHARS.length)]))
|
||||
.join(""),
|
||||
);
|
||||
if (frame++ > target.length * 3) clearInterval(id);
|
||||
}, 30);
|
||||
}
|
||||
|
||||
<button onClick={() => scramble("StyleSeed")}>{text}</button>`,
|
||||
},
|
||||
{
|
||||
key: "confetti-pop",
|
||||
label: "Confetti",
|
||||
category: "flair",
|
||||
vibe: "Particle burst on success — celebrate the click",
|
||||
seed: "spring",
|
||||
snippet: `const COLORS = ["#FF6B6B", "#FFD93D", "#6C5CE7", "#4ECDC4"];
|
||||
const [bits, setBits] = useState<number[]>([]);
|
||||
|
||||
<button onClick={() => setBits(Array.from({ length: 16 }, (_, i) => i))} className="relative">
|
||||
Celebrate
|
||||
{bits.map((i) => (
|
||||
<motion.span
|
||||
key={i}
|
||||
initial={{ x: 0, y: 0, opacity: 1 }}
|
||||
animate={{ x: (Math.random() - 0.5) * 180, y: (Math.random() - 0.5) * 180, opacity: 0, rotate: Math.random() * 360 }}
|
||||
transition={{ duration: 0.8, ease: "easeOut" }}
|
||||
onAnimationComplete={() => setBits([])}
|
||||
style={{ position: "absolute", left: "50%", top: "50%", width: 8, height: 8, background: COLORS[i % 4] }}
|
||||
/>
|
||||
))}
|
||||
</button>`,
|
||||
},
|
||||
|
||||
// ── Toggle ───────────────────────────────────────────────
|
||||
{
|
||||
key: "toggle-flip",
|
||||
label: "Flip",
|
||||
category: "toggle",
|
||||
vibe: "3D Y-axis card flip between two faces",
|
||||
seed: "spring",
|
||||
snippet: `const [on, setOn] = useState(false);
|
||||
|
||||
<motion.button
|
||||
onClick={() => setOn((o) => !o)}
|
||||
animate={{ rotateY: on ? 180 : 0 }}
|
||||
transition={{ type: "spring", stiffness: 260, damping: 22 }}
|
||||
style={{ transformStyle: "preserve-3d", perspective: 800 }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "toggle-slide",
|
||||
label: "Slide stack",
|
||||
category: "toggle",
|
||||
vibe: "Old value slides out, new slides in from the side",
|
||||
seed: "snap",
|
||||
snippet: `<AnimatePresence mode="popLayout" initial={false}>
|
||||
<motion.div
|
||||
key={index}
|
||||
initial={{ x: 40, opacity: 0 }}
|
||||
animate={{ x: 0, opacity: 1 }}
|
||||
exit={{ x: -40, opacity: 0 }}
|
||||
transition={{ type: "spring", stiffness: 320, damping: 30 }}
|
||||
>
|
||||
{value}
|
||||
</motion.div>
|
||||
</AnimatePresence>`,
|
||||
},
|
||||
{
|
||||
key: "toggle-morph",
|
||||
label: "Morph",
|
||||
category: "toggle",
|
||||
vibe: "Shape morphs — pill ⇄ circle, width + radius",
|
||||
seed: "silk",
|
||||
snippet: `const [on, setOn] = useState(false);
|
||||
|
||||
<motion.button
|
||||
onClick={() => setOn((o) => !o)}
|
||||
animate={{ borderRadius: on ? 999 : 16, width: on ? 56 : 160 }}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 26 }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "toggle-curtain",
|
||||
label: "Curtain",
|
||||
category: "toggle",
|
||||
vibe: "Top→bottom clip-path wipe reveals the panel",
|
||||
seed: "silk",
|
||||
snippet: `const [open, setOpen] = useState(false);
|
||||
|
||||
<motion.div
|
||||
initial={false}
|
||||
animate={{ clipPath: open ? "inset(0 0 0% 0)" : "inset(0 0 100% 0)" }}
|
||||
transition={{ ease: [0.4, 0, 0.2, 1], duration: 0.4 }}
|
||||
/>`,
|
||||
},
|
||||
|
||||
// ── Reveal ───────────────────────────────────────────────
|
||||
{
|
||||
key: "reveal-blur",
|
||||
label: "Blur in",
|
||||
category: "reveal",
|
||||
vibe: "Focus-pulls into place from a soft blur",
|
||||
seed: "float",
|
||||
snippet: `<motion.div
|
||||
initial={{ opacity: 0, filter: "blur(12px)", scale: 0.96 }}
|
||||
animate={{ opacity: 1, filter: "blur(0px)", scale: 1 }}
|
||||
transition={{ duration: 0.6, ease: "easeOut" }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "reveal-rise",
|
||||
label: "Text rise",
|
||||
category: "reveal",
|
||||
vibe: "Masked clip-path rise — text climbs into view",
|
||||
seed: "silk",
|
||||
snippet: `<motion.div
|
||||
initial={{ clipPath: "inset(100% 0 0 0)", y: 12 }}
|
||||
animate={{ clipPath: "inset(0% 0 0 0)", y: 0 }}
|
||||
transition={{ duration: 0.5, ease: [0.32, 0.72, 0, 1] }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "reveal-unfold",
|
||||
label: "Unfold",
|
||||
category: "reveal",
|
||||
vibe: "scaleY from the top edge, like an accordion",
|
||||
seed: "spring",
|
||||
snippet: `<motion.div
|
||||
style={{ transformOrigin: "top" }}
|
||||
initial={{ scaleY: 0, opacity: 0 }}
|
||||
animate={{ scaleY: 1, opacity: 1 }}
|
||||
transition={{ type: "spring", stiffness: 300, damping: 30 }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "pop-in",
|
||||
label: "Pop in",
|
||||
category: "reveal",
|
||||
vibe: "Spring overshoot from zero — bouncy arrival",
|
||||
seed: "spring",
|
||||
snippet: `<motion.div
|
||||
initial={{ scale: 0, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ type: "spring", stiffness: 500, damping: 16 }}
|
||||
/>`,
|
||||
},
|
||||
|
||||
// ── Press ────────────────────────────────────────────────
|
||||
{
|
||||
key: "press-squish",
|
||||
label: "Squish",
|
||||
category: "press",
|
||||
vibe: "Scale-down + tiny skew — jelly press",
|
||||
seed: "spring",
|
||||
snippet: `<motion.button
|
||||
whileTap={{ scale: 0.9, skewX: -4 }}
|
||||
transition={{ type: "spring", stiffness: 600, damping: 18 }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "tap-ripple",
|
||||
label: "Ripple",
|
||||
category: "press",
|
||||
vibe: "Material-style radial ripple from the tap point",
|
||||
seed: "snap",
|
||||
snippet: `const [ripples, setRipples] = useState<{ id: number; x: number; y: number }[]>([]);
|
||||
|
||||
function onTap(e: React.PointerEvent) {
|
||||
const r = e.currentTarget.getBoundingClientRect();
|
||||
setRipples((rs) => [...rs, { id: performance.now(), x: e.clientX - r.left, y: e.clientY - r.top }]);
|
||||
}
|
||||
|
||||
<button onPointerDown={onTap} className="relative overflow-hidden">
|
||||
{ripples.map((r) => (
|
||||
<motion.span
|
||||
key={r.id}
|
||||
initial={{ scale: 0, opacity: 0.4 }}
|
||||
animate={{ scale: 4, opacity: 0 }}
|
||||
transition={{ duration: 0.6, ease: "easeOut" }}
|
||||
onAnimationComplete={() => setRipples((rs) => rs.filter((x) => x.id !== r.id))}
|
||||
style={{ position: "absolute", left: r.x, top: r.y, width: 40, height: 40, borderRadius: 999, background: "currentColor" }}
|
||||
/>
|
||||
))}
|
||||
</button>`,
|
||||
},
|
||||
|
||||
// ── Attention ────────────────────────────────────────────
|
||||
{
|
||||
key: "pulse-beat",
|
||||
label: "Heartbeat",
|
||||
category: "attention",
|
||||
vibe: "Looping scale pulse — alive, rhythmic",
|
||||
seed: "pulse",
|
||||
snippet: `<motion.div
|
||||
animate={{ scale: [1, 1.12, 1] }}
|
||||
transition={{ duration: 1.1, repeat: Infinity, ease: "easeInOut" }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "wiggle",
|
||||
label: "Wiggle",
|
||||
category: "attention",
|
||||
vibe: "Quick horizontal shake — error / wrong input",
|
||||
seed: "snap",
|
||||
snippet: `<motion.div
|
||||
animate={shake ? { x: [0, -6, 6, -4, 4, 0] } : { x: 0 }}
|
||||
transition={{ duration: 0.4 }}
|
||||
/>`,
|
||||
},
|
||||
{
|
||||
key: "shimmer",
|
||||
label: "Shimmer",
|
||||
category: "attention",
|
||||
vibe: "Skeleton loading sweep across a surface",
|
||||
seed: "silk",
|
||||
snippet: `<motion.div
|
||||
animate={{ backgroundPosition: ["200% 0", "-200% 0"] }}
|
||||
transition={{ duration: 1.5, repeat: Infinity, ease: "linear" }}
|
||||
style={{
|
||||
background: "linear-gradient(90deg,#eee 25%,#f5f5f5 50%,#eee 75%)",
|
||||
backgroundSize: "200% 100%",
|
||||
}}
|
||||
/>`,
|
||||
},
|
||||
|
||||
// ── List ─────────────────────────────────────────────────
|
||||
{
|
||||
key: "stagger-cascade",
|
||||
label: "Cascade",
|
||||
category: "list",
|
||||
vibe: "Children fade-up one after another",
|
||||
seed: "silk",
|
||||
snippet: `<motion.ul initial="hidden" animate="show"
|
||||
variants={{ show: { transition: { staggerChildren: 0.07 } } }}>
|
||||
{items.map((item) => (
|
||||
<motion.li
|
||||
key={item.id}
|
||||
variants={{ hidden: { opacity: 0, y: 12 }, show: { opacity: 1, y: 0 } }}
|
||||
>
|
||||
{item.label}
|
||||
</motion.li>
|
||||
))}
|
||||
</motion.ul>`,
|
||||
},
|
||||
];
|
||||
|
||||
/** Keyword → entry, for the /ss-motion skill and Copy lookups. */
|
||||
export const MOTION_BY_KEY: Record<string, MotionKeyword> = Object.fromEntries(
|
||||
MOTION_LIBRARY.map((m) => [m.key, m]),
|
||||
);
|
||||
@@ -0,0 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/**
|
||||
* Subscribes to `prefers-reduced-motion: reduce` and returns the current value.
|
||||
*
|
||||
* Use this to swap any seed recipe for a near-instant variant when the user
|
||||
* has asked the OS to dampen motion. Server-side rendering returns `false`
|
||||
* (no reduction), then hydration updates if needed.
|
||||
*/
|
||||
export function usePrefersReducedMotion(): boolean {
|
||||
const [reduced, setReduced] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof window === "undefined" || !window.matchMedia) return;
|
||||
const mql = window.matchMedia("(prefers-reduced-motion: reduce)");
|
||||
setReduced(mql.matches);
|
||||
const handler = (e: MediaQueryListEvent) => setReduced(e.matches);
|
||||
mql.addEventListener("change", handler);
|
||||
return () => mql.removeEventListener("change", handler);
|
||||
}, []);
|
||||
|
||||
return reduced;
|
||||
}
|
||||
|
||||
/**
|
||||
* A flat-instant transition. Use as a replacement for any seed transition
|
||||
* when the user prefers reduced motion.
|
||||
*/
|
||||
export const REDUCED_TRANSITION = { duration: 0.01 } as const;
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { SeedConfig } from "../contexts";
|
||||
|
||||
/**
|
||||
* Float — weightless, gentle, dreamy.
|
||||
*
|
||||
* Use for: marketing surfaces, hero sections, anything that should feel
|
||||
* like content drifting in from elsewhere. Long durations, soft easing,
|
||||
* larger displacements than Silk. Reads as "this place takes its time."
|
||||
* Inspirations: Apple product pages, editorial sites, ambient UIs.
|
||||
*/
|
||||
export const float: SeedConfig = {
|
||||
name: "Float",
|
||||
vibe: "weightless, gentle, dreamy",
|
||||
entrance: {
|
||||
initial: { opacity: 0, y: 24 },
|
||||
animate: {
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
transition: { ease: [0.22, 1, 0.36, 1], duration: 0.7 },
|
||||
},
|
||||
},
|
||||
exit: {
|
||||
exit: {
|
||||
opacity: 0,
|
||||
y: -20,
|
||||
transition: { ease: [0.4, 0, 1, 1], duration: 0.5 },
|
||||
},
|
||||
},
|
||||
hover: {
|
||||
whileHover: {
|
||||
y: -3,
|
||||
transition: { ease: [0.22, 1, 0.36, 1], duration: 0.5 },
|
||||
},
|
||||
},
|
||||
press: {
|
||||
whileTap: {
|
||||
scale: 0.97,
|
||||
y: 1,
|
||||
transition: { ease: [0.4, 0, 0.2, 1], duration: 0.3 },
|
||||
},
|
||||
},
|
||||
layout: {
|
||||
layout: true,
|
||||
transition: { ease: [0.22, 1, 0.36, 1], duration: 0.55 },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { SeedConfig } from "../contexts";
|
||||
|
||||
/**
|
||||
* Pulse — rhythmic, alive, punchy.
|
||||
*
|
||||
* Use for: notifications, live feeds, anything that should feel like a
|
||||
* heartbeat. Tight spring (low mass, high stiffness) for quick, percussive
|
||||
* motion that doesn't overstay its welcome.
|
||||
* Inspirations: Discord, music apps, status indicators.
|
||||
*/
|
||||
export const pulse: SeedConfig = {
|
||||
name: "Pulse",
|
||||
vibe: "rhythmic, alive, punchy",
|
||||
entrance: {
|
||||
initial: { opacity: 0, scale: 0.9 },
|
||||
animate: {
|
||||
opacity: 1,
|
||||
scale: 1,
|
||||
transition: { type: "spring", stiffness: 500, damping: 25, mass: 0.6 },
|
||||
},
|
||||
},
|
||||
exit: {
|
||||
exit: {
|
||||
opacity: 0,
|
||||
scale: 0.95,
|
||||
transition: { type: "spring", stiffness: 400, damping: 30, mass: 0.6 },
|
||||
},
|
||||
},
|
||||
hover: {
|
||||
whileHover: {
|
||||
scale: 1.02,
|
||||
transition: { type: "spring", stiffness: 500, damping: 25, mass: 0.6 },
|
||||
},
|
||||
},
|
||||
press: {
|
||||
whileTap: {
|
||||
scale: 0.94,
|
||||
transition: { type: "spring", stiffness: 600, damping: 28, mass: 0.6 },
|
||||
},
|
||||
},
|
||||
layout: {
|
||||
layout: true,
|
||||
transition: { type: "spring", stiffness: 500, damping: 25, mass: 0.6 },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { SeedConfig } from "../contexts";
|
||||
|
||||
/**
|
||||
* Silk — smooth, elegant, continuous.
|
||||
*
|
||||
* Use for: editorial layouts, financial dashboards, anything that should
|
||||
* feel composed and quiet. No bounce, no overshoot, just calibrated easing.
|
||||
* Inspirations: Stripe, Linear (modals), Notion.
|
||||
*/
|
||||
export const silk: SeedConfig = {
|
||||
name: "Silk",
|
||||
vibe: "smooth, elegant, continuous",
|
||||
entrance: {
|
||||
initial: { opacity: 0, y: 12 },
|
||||
animate: {
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
transition: { ease: [0.32, 0.72, 0, 1], duration: 0.45 },
|
||||
},
|
||||
},
|
||||
exit: {
|
||||
exit: {
|
||||
opacity: 0,
|
||||
y: -6,
|
||||
transition: { ease: [0.4, 0, 1, 1], duration: 0.3 },
|
||||
},
|
||||
},
|
||||
hover: {
|
||||
whileHover: {
|
||||
y: -1,
|
||||
filter: "brightness(1.03)",
|
||||
transition: { ease: [0.32, 0.72, 0, 1], duration: 0.25 },
|
||||
},
|
||||
},
|
||||
press: {
|
||||
whileTap: {
|
||||
scale: 0.98,
|
||||
transition: { ease: [0.4, 0, 0.2, 1], duration: 0.15 },
|
||||
},
|
||||
},
|
||||
layout: {
|
||||
layout: true,
|
||||
transition: { ease: [0.32, 0.72, 0, 1], duration: 0.4 },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { SeedConfig } from "../contexts";
|
||||
|
||||
/**
|
||||
* Snap — instant, decisive, precise.
|
||||
*
|
||||
* Use for: power-user tools, keyboard-driven UIs, anything that should
|
||||
* feel like a terminal command landing. Short durations, sharp easing,
|
||||
* no bounce. The interaction is over before you notice the animation.
|
||||
* Inspirations: Raycast, Linear, command palettes.
|
||||
*/
|
||||
export const snap: SeedConfig = {
|
||||
name: "Snap",
|
||||
vibe: "instant, decisive, precise",
|
||||
entrance: {
|
||||
initial: { opacity: 0 },
|
||||
animate: {
|
||||
opacity: 1,
|
||||
transition: { ease: [0, 0, 0.2, 1], duration: 0.18 },
|
||||
},
|
||||
},
|
||||
exit: {
|
||||
exit: {
|
||||
opacity: 0,
|
||||
transition: { ease: [0.4, 0, 1, 1], duration: 0.12 },
|
||||
},
|
||||
},
|
||||
hover: {
|
||||
whileHover: {
|
||||
filter: "brightness(1.08)",
|
||||
transition: { ease: [0.4, 0, 0.2, 1], duration: 0.1 },
|
||||
},
|
||||
},
|
||||
press: {
|
||||
whileTap: {
|
||||
scale: 0.97,
|
||||
transition: { ease: [0.4, 0, 0.2, 1], duration: 0.06 },
|
||||
},
|
||||
},
|
||||
layout: {
|
||||
layout: true,
|
||||
transition: { ease: [0.4, 0, 0.2, 1], duration: 0.18 },
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { SeedConfig } from "../contexts";
|
||||
|
||||
/**
|
||||
* Spring — bouncy, energetic, playful.
|
||||
*
|
||||
* Use for: CTA buttons, success states, anything that should feel alive.
|
||||
* Inspirations: Arc, Toss (primary CTA), Discord.
|
||||
*/
|
||||
export const spring: SeedConfig = {
|
||||
name: "Spring",
|
||||
vibe: "bouncy, energetic, playful",
|
||||
entrance: {
|
||||
initial: { opacity: 0, y: 16, scale: 0.96 },
|
||||
animate: {
|
||||
opacity: 1,
|
||||
y: 0,
|
||||
scale: 1,
|
||||
transition: { type: "spring", stiffness: 300, damping: 18, mass: 1 },
|
||||
},
|
||||
},
|
||||
exit: {
|
||||
exit: {
|
||||
opacity: 0,
|
||||
y: -8,
|
||||
scale: 0.98,
|
||||
transition: { type: "spring", stiffness: 400, damping: 30, mass: 0.8 },
|
||||
},
|
||||
},
|
||||
hover: {
|
||||
whileHover: {
|
||||
scale: 1.04,
|
||||
y: -2,
|
||||
transition: { type: "spring", stiffness: 300, damping: 20 },
|
||||
},
|
||||
},
|
||||
press: {
|
||||
whileTap: {
|
||||
scale: 0.96,
|
||||
transition: { type: "spring", stiffness: 500, damping: 30 },
|
||||
},
|
||||
},
|
||||
layout: {
|
||||
layout: true,
|
||||
transition: { type: "spring", stiffness: 300, damping: 20, mass: 0.8 },
|
||||
},
|
||||
};
|
||||
@@ -1,614 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import {
|
||||
METRICS,
|
||||
type ChampionPoolEntryDto,
|
||||
type LeadMetricDto,
|
||||
type MetricId,
|
||||
type MetricValueDto,
|
||||
type PlayerAnalysisDto,
|
||||
type SimilarMetricDto,
|
||||
type SimilarPlayerDto,
|
||||
type SimilarPlayersDto,
|
||||
type TierComparison,
|
||||
type TierInfoDto,
|
||||
} from '@persona-lenz/shared';
|
||||
import {
|
||||
PolarAngleAxis,
|
||||
PolarGrid,
|
||||
PolarRadiusAxis,
|
||||
Radar,
|
||||
RadarChart,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
} from 'recharts';
|
||||
import {
|
||||
getLatestPlayerAnalysis,
|
||||
getReadableErrorMessage,
|
||||
getSimilarPlayers,
|
||||
} from '../api/analysis';
|
||||
import {
|
||||
loadChampionCatalog,
|
||||
type ChampionCatalog,
|
||||
} from '../api/data-dragon';
|
||||
import {
|
||||
formatPercent,
|
||||
formatTier,
|
||||
getMetricDescription,
|
||||
getMetricDirectionLabel,
|
||||
getMetricLabel,
|
||||
ROLE_LABELS,
|
||||
} from '../lib/format';
|
||||
|
||||
interface RadarMetricDatum {
|
||||
metricId: MetricId;
|
||||
metricLabel: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
const SIMILAR_PLAYER_LIMIT = 10;
|
||||
|
||||
export function DashboardPage() {
|
||||
const { puuid } = useParams<{ puuid: string }>();
|
||||
const [analysis, setAnalysis] = useState<PlayerAnalysisDto | null>(null);
|
||||
const [championCatalog, setChampionCatalog] =
|
||||
useState<ChampionCatalog | null>(null);
|
||||
const [similarPlayers, setSimilarPlayers] =
|
||||
useState<SimilarPlayersDto | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [similarPlayersErrorMessage, setSimilarPlayersErrorMessage] =
|
||||
useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const missingPuuidMessage = puuid ? null : '플레이어 식별자가 없습니다.';
|
||||
|
||||
useEffect(() => {
|
||||
if (!puuid) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentPuuid = puuid;
|
||||
let isActive = true;
|
||||
|
||||
async function loadDashboard() {
|
||||
setIsLoading(true);
|
||||
setAnalysis(null);
|
||||
setErrorMessage(null);
|
||||
setSimilarPlayersErrorMessage(null);
|
||||
setSimilarPlayers(null);
|
||||
|
||||
const similarPlayersResultPromise = getSimilarPlayers(
|
||||
currentPuuid,
|
||||
SIMILAR_PLAYER_LIMIT,
|
||||
).then(
|
||||
(value) => ({ status: 'fulfilled', value }) as const,
|
||||
(reason: unknown) => ({ status: 'rejected', reason }) as const,
|
||||
);
|
||||
|
||||
try {
|
||||
const nextAnalysis = await getLatestPlayerAnalysis(currentPuuid);
|
||||
|
||||
if (!isActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
setAnalysis(nextAnalysis);
|
||||
} catch (error) {
|
||||
if (isActive) {
|
||||
setAnalysis(null);
|
||||
setErrorMessage(getReadableErrorMessage(error));
|
||||
setIsLoading(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isActive) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
const similarPlayersResult = await similarPlayersResultPromise;
|
||||
|
||||
if (!isActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (similarPlayersResult.status === 'fulfilled') {
|
||||
setSimilarPlayers(similarPlayersResult.value);
|
||||
} else {
|
||||
setSimilarPlayersErrorMessage(
|
||||
getReadableErrorMessage(similarPlayersResult.reason),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void loadDashboard();
|
||||
|
||||
return () => {
|
||||
isActive = false;
|
||||
};
|
||||
}, [puuid]);
|
||||
|
||||
useEffect(() => {
|
||||
let isActive = true;
|
||||
|
||||
async function loadChampions() {
|
||||
try {
|
||||
const catalog = await loadChampionCatalog();
|
||||
|
||||
if (isActive) {
|
||||
setChampionCatalog(catalog);
|
||||
}
|
||||
} catch {
|
||||
if (isActive) {
|
||||
setChampionCatalog(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void loadChampions();
|
||||
|
||||
return () => {
|
||||
isActive = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const radarData = useMemo<RadarMetricDatum[]>(() => {
|
||||
if (!analysis) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return METRICS.filter((metric) => metric.includeInVector).map((metric) => ({
|
||||
metricId: metric.id,
|
||||
metricLabel: metric.label,
|
||||
value: Math.round((analysis.profile.playstyle[metric.id] ?? 0) * 100),
|
||||
}));
|
||||
}, [analysis]);
|
||||
|
||||
if (!missingPuuidMessage && isLoading) {
|
||||
return <DashboardSkeleton />;
|
||||
}
|
||||
|
||||
if (missingPuuidMessage || errorMessage || !analysis) {
|
||||
return (
|
||||
<section className="empty-view" aria-labelledby="dashboard-error-title">
|
||||
<p className="eyebrow">Analysis result</p>
|
||||
<h1 id="dashboard-error-title">결과를 불러오지 못했습니다.</h1>
|
||||
<p className="message message-error" role="alert">
|
||||
{missingPuuidMessage ?? errorMessage ?? '분석 결과가 없습니다.'}
|
||||
</p>
|
||||
<Link className="primary-action" to="/">
|
||||
새 분석 요청
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const soloTier = pickSoloTier(analysis.account.tiers);
|
||||
const sampleIsLow = analysis.profile.sampleGameCount < 5;
|
||||
|
||||
return (
|
||||
<article className="dashboard-view" aria-labelledby="dashboard-title">
|
||||
<section className="dashboard-summary">
|
||||
<div>
|
||||
<p className="eyebrow">Player analysis</p>
|
||||
<h1 id="dashboard-title">
|
||||
{analysis.account.gameName}#{analysis.account.tagLine}
|
||||
</h1>
|
||||
<p className="lead-copy">
|
||||
{soloTier ? formatTier(soloTier) : '랭크 정보 없음'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="summary-stat-grid" aria-label="요약 지표">
|
||||
<SummaryStat label="주 포지션" value={ROLE_LABELS[analysis.profile.mainRole]} />
|
||||
<SummaryStat
|
||||
label="분석 게임"
|
||||
value={`${analysis.profile.sampleGameCount}게임`}
|
||||
/>
|
||||
<SummaryStat
|
||||
label="신뢰도"
|
||||
value={formatPercent(analysis.profile.confidence)}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{sampleIsLow ? (
|
||||
<p className="message message-warning" role="status">
|
||||
표본 부족: 유효 랭크 게임이 5게임 미만이라 지표 신뢰도가 낮습니다.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<section className="chart-section" aria-labelledby="radar-title">
|
||||
<div className="section-heading">
|
||||
<h2 id="radar-title">플레이스타일 벡터</h2>
|
||||
<span className="status-pill">
|
||||
schema v{analysis.profile.featureSchemaVersion}
|
||||
</span>
|
||||
</div>
|
||||
<div className="radar-frame">
|
||||
<ResponsiveContainer height={380} width="100%">
|
||||
<RadarChart data={radarData} outerRadius="72%">
|
||||
<PolarGrid stroke="#31413b" />
|
||||
<PolarAngleAxis
|
||||
dataKey="metricLabel"
|
||||
tick={{ fill: '#c7d3cc', fontSize: 11 }}
|
||||
/>
|
||||
<PolarRadiusAxis
|
||||
angle={90}
|
||||
domain={[0, 100]}
|
||||
stroke="#748079"
|
||||
tick={{ fill: '#9fa9a3', fontSize: 10 }}
|
||||
tickCount={5}
|
||||
/>
|
||||
<Tooltip formatter={(value) => [`${value}%`, '정규화 값']} />
|
||||
<Radar
|
||||
dataKey="value"
|
||||
fill="#4cc9a7"
|
||||
fillOpacity={0.24}
|
||||
name="플레이스타일"
|
||||
stroke="#4cc9a7"
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</RadarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="insight-grid" aria-label="강점과 약점">
|
||||
<MetricInsightList
|
||||
description="방향성을 반영했을 때 현재 프로필에서 상대적으로 좋은 순서입니다."
|
||||
title="강점 지표"
|
||||
values={analysis.strengths}
|
||||
/>
|
||||
<MetricInsightList
|
||||
description="방향성을 반영했을 때 개선 여지가 큰 순서입니다."
|
||||
title="약점 지표"
|
||||
values={analysis.weaknesses}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section className="champion-section" aria-labelledby="champion-title">
|
||||
<div className="section-heading">
|
||||
<h2 id="champion-title">챔피언 풀</h2>
|
||||
{championCatalog ? (
|
||||
<span className="status-pill">Data Dragon {championCatalog.version}</span>
|
||||
) : (
|
||||
<span className="status-pill">metadata unavailable</span>
|
||||
)}
|
||||
</div>
|
||||
{analysis.profile.championPool.length > 0 ? (
|
||||
<div className="champion-list">
|
||||
{analysis.profile.championPool.map((entry) => (
|
||||
<ChampionPoolRow
|
||||
catalog={championCatalog}
|
||||
entry={entry}
|
||||
key={entry.championId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="empty-copy">분석 가능한 챔피언 기록이 없습니다.</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<SimilarPlayerSection
|
||||
catalog={championCatalog}
|
||||
errorMessage={similarPlayersErrorMessage}
|
||||
similarPlayers={similarPlayers}
|
||||
/>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function DashboardSkeleton() {
|
||||
return (
|
||||
<section className="dashboard-view" aria-busy="true" aria-label="결과 로딩 중">
|
||||
<div className="skeleton skeleton-title" />
|
||||
<div className="skeleton-grid">
|
||||
<div className="skeleton skeleton-panel" />
|
||||
<div className="skeleton skeleton-panel" />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function SummaryStat({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div className="summary-stat">
|
||||
<span>{label}</span>
|
||||
<strong>{value}</strong>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MetricInsightList({
|
||||
description,
|
||||
title,
|
||||
values,
|
||||
}: {
|
||||
description: string;
|
||||
title: string;
|
||||
values: MetricValueDto[];
|
||||
}) {
|
||||
return (
|
||||
<section className="insight-section">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<h2>{title}</h2>
|
||||
<p className="section-copy">{description}</p>
|
||||
</div>
|
||||
<span className="status-pill">{values.length} metrics</span>
|
||||
</div>
|
||||
<div className="metric-card-list">
|
||||
{values.map((metricValue) => (
|
||||
<article className="metric-card" key={metricValue.metricId}>
|
||||
<div className="metric-card-heading">
|
||||
<h3>{getMetricLabel(metricValue.metricId)}</h3>
|
||||
<strong>{formatPercent(metricValue.value)}</strong>
|
||||
</div>
|
||||
<p>{getMetricDescription(metricValue.metricId)}</p>
|
||||
<span>{getMetricDirectionLabel(metricValue.metricId)}</span>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function ChampionPoolRow({
|
||||
catalog,
|
||||
entry,
|
||||
}: {
|
||||
catalog: ChampionCatalog | null;
|
||||
entry: ChampionPoolEntryDto;
|
||||
}) {
|
||||
const champion = catalog?.champions[entry.championId];
|
||||
const winRate = entry.games > 0 ? entry.wins / entry.games : 0;
|
||||
|
||||
return (
|
||||
<article className="champion-row">
|
||||
{champion ? (
|
||||
<img alt="" className="champion-icon" height="44" src={champion.imageUrl} width="44" />
|
||||
) : (
|
||||
<span className="champion-icon champion-placeholder" aria-hidden="true" />
|
||||
)}
|
||||
<div className="champion-copy">
|
||||
<strong>{champion?.name ?? `챔피언 ${entry.championId}`}</strong>
|
||||
<span>
|
||||
{entry.games}게임 · {entry.wins}승 · 승률 {formatPercent(winRate)}
|
||||
</span>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function SimilarPlayerSection({
|
||||
catalog,
|
||||
errorMessage,
|
||||
similarPlayers,
|
||||
}: {
|
||||
catalog: ChampionCatalog | null;
|
||||
errorMessage: string | null;
|
||||
similarPlayers: SimilarPlayersDto | null;
|
||||
}) {
|
||||
const matches = similarPlayers?.matches ?? [];
|
||||
|
||||
return (
|
||||
<section className="similar-section" aria-labelledby="similar-title">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<h2 id="similar-title">나와 비슷한 플레이어</h2>
|
||||
<p className="section-copy">
|
||||
플레이스타일 벡터가 가장 가까운 유저들입니다. 티어가 다르다면 어떤
|
||||
지표에서 차이가 나는지 확인해보세요.
|
||||
</p>
|
||||
</div>
|
||||
<span className="status-pill">
|
||||
{similarPlayers ? `${matches.length} players` : 'similar players'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{errorMessage ? (
|
||||
<p className="message message-warning similar-message" role="status">
|
||||
비슷한 플레이어 목록을 불러오지 못했습니다. {errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!errorMessage && similarPlayers && matches.length === 0 ? (
|
||||
<p className="empty-copy">
|
||||
비교 가능한 프로필이 아직 충분히 수집되지 않았습니다.
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!errorMessage && !similarPlayers ? (
|
||||
<p className="empty-copy">비슷한 플레이어를 찾는 중입니다.</p>
|
||||
) : null}
|
||||
|
||||
{matches.length > 0 ? (
|
||||
<div
|
||||
aria-label="나와 비슷한 플레이어 테이블"
|
||||
className="similar-table-wrap"
|
||||
role="region"
|
||||
tabIndex={0}
|
||||
>
|
||||
<table className="similar-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">플레이어</th>
|
||||
<th scope="col">유사도</th>
|
||||
<th scope="col">주요 챔피언</th>
|
||||
<th scope="col">비교 지표</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{matches.map((match) => (
|
||||
<tr key={match.displayId}>
|
||||
<td>
|
||||
<div className="similar-player">
|
||||
<strong>{formatSimilarPlayerName(match)}</strong>
|
||||
<span>
|
||||
{formatSimilarPlayerTier(match)} ·{' '}
|
||||
{ROLE_LABELS[match.mainRole]} ·{' '}
|
||||
{match.sampleGameCount}게임
|
||||
</span>
|
||||
{formatTierComparison(match.tierComparison) ? (
|
||||
<span className="similar-tier-badge">
|
||||
{formatTierComparison(match.tierComparison)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<div className="similar-score">
|
||||
<strong>{formatPercent(match.similarityScore)}</strong>
|
||||
<span>종합 {formatPercent(match.finalScore)}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<SimilarPlayerChampionList catalog={catalog} match={match} />
|
||||
</td>
|
||||
<td>
|
||||
<div className="similar-metric-groups">
|
||||
<LeadMetricChips
|
||||
accent
|
||||
emptyLabel="이 유저가 앞서는 지표 없음"
|
||||
title="이 유저가 앞서는 지표"
|
||||
values={match.strongerMetrics}
|
||||
/>
|
||||
<LeadMetricChips
|
||||
emptyLabel={null}
|
||||
title="내가 앞서는 지표"
|
||||
values={match.weakerMetrics}
|
||||
/>
|
||||
<SimilarMetricChips values={match.similarMetrics} />
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function SimilarPlayerChampionList({
|
||||
catalog,
|
||||
match,
|
||||
}: {
|
||||
catalog: ChampionCatalog | null;
|
||||
match: SimilarPlayerDto;
|
||||
}) {
|
||||
if (match.mainChampions.length === 0) {
|
||||
return <span className="similar-empty">챔피언 기록 없음</span>;
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="similar-chip-list">
|
||||
{match.mainChampions.map((entry) => (
|
||||
<li className="similar-chip" key={entry.championId}>
|
||||
<strong>{formatChampionName(catalog, entry.championId)}</strong>
|
||||
<span>{entry.games}게임</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function LeadMetricChips({
|
||||
accent = false,
|
||||
emptyLabel,
|
||||
title,
|
||||
values,
|
||||
}: {
|
||||
accent?: boolean;
|
||||
emptyLabel: string | null;
|
||||
title: string;
|
||||
values: LeadMetricDto[];
|
||||
}) {
|
||||
if (values.length === 0) {
|
||||
return emptyLabel ? (
|
||||
<span className="similar-empty">{emptyLabel}</span>
|
||||
) : null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="similar-metric-group">
|
||||
<span>{title}</span>
|
||||
<ul className="similar-chip-list">
|
||||
{values.map((value) => (
|
||||
<li
|
||||
className={`similar-chip ${accent ? 'similar-chip-accent' : ''}`}
|
||||
key={value.metricId}
|
||||
>
|
||||
<strong>{getMetricLabel(value.metricId)}</strong>
|
||||
<span>+{formatPercent(value.lead)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SimilarMetricChips({ values }: { values: SimilarMetricDto[] }) {
|
||||
if (values.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="similar-metric-group">
|
||||
<span>비슷한 지표</span>
|
||||
<ul className="similar-chip-list">
|
||||
{values.map((value) => (
|
||||
<li className="similar-chip similar-chip-muted" key={value.metricId}>
|
||||
<strong>{getMetricLabel(value.metricId)}</strong>
|
||||
<span>차이 {formatPercent(value.absoluteGap)}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatSimilarPlayerName(match: SimilarPlayerDto): string {
|
||||
if (match.riotId) {
|
||||
return `${match.riotId.gameName}#${match.riotId.tagLine}`;
|
||||
}
|
||||
|
||||
return formatSimilarPlayerDisplayId(match.displayId);
|
||||
}
|
||||
|
||||
function formatSimilarPlayerDisplayId(displayId: string): string {
|
||||
const numericSuffix = displayId.match(/^similar-(\d+)$/)?.[1];
|
||||
|
||||
return numericSuffix ? `비슷한 플레이어 #${numericSuffix}` : '비슷한 플레이어';
|
||||
}
|
||||
|
||||
function formatTierComparison(tierComparison: TierComparison): string | null {
|
||||
if (tierComparison === 'higher') return '나보다 높은 티어';
|
||||
if (tierComparison === 'lower') return '나보다 낮은 티어';
|
||||
if (tierComparison === 'same') return '같은 티어';
|
||||
return null;
|
||||
}
|
||||
|
||||
function formatSimilarPlayerTier(match: SimilarPlayerDto): string {
|
||||
const tier = [match.tier, match.division].filter(Boolean).join(' ');
|
||||
|
||||
if (!tier) {
|
||||
return '랭크 정보 없음';
|
||||
}
|
||||
|
||||
return typeof match.leaguePoints === 'number'
|
||||
? `${tier} ${match.leaguePoints}LP`
|
||||
: tier;
|
||||
}
|
||||
|
||||
function formatChampionName(
|
||||
catalog: ChampionCatalog | null,
|
||||
championId: number,
|
||||
): string {
|
||||
return catalog?.champions[championId]?.name ?? `챔피언 ${championId}`;
|
||||
}
|
||||
|
||||
function pickSoloTier(tiers: TierInfoDto[]): TierInfoDto | null {
|
||||
return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0] ?? null;
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import { useState, type FormEvent } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { getReadableErrorMessage, requestAnalysis } from '../api/analysis';
|
||||
import { saveAnalysisRequest } from '../lib/analysis-request-cache';
|
||||
|
||||
const DEFAULT_MATCH_COUNT = 20;
|
||||
const GAME_NAME_MIN_LENGTH = 3;
|
||||
const GAME_NAME_MAX_LENGTH = 16;
|
||||
const TAG_LINE_MIN_LENGTH = 3;
|
||||
const TAG_LINE_MAX_LENGTH = 5;
|
||||
|
||||
export function HomePage() {
|
||||
const navigate = useNavigate();
|
||||
const [gameName, setGameName] = useState('');
|
||||
const [tagLine, setTagLine] = useState('');
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const trimmedGameName = gameName.trim();
|
||||
const trimmedTagLine = tagLine.trim();
|
||||
const canSubmit =
|
||||
trimmedGameName.length >= GAME_NAME_MIN_LENGTH &&
|
||||
trimmedGameName.length <= GAME_NAME_MAX_LENGTH &&
|
||||
trimmedTagLine.length >= TAG_LINE_MIN_LENGTH &&
|
||||
trimmedTagLine.length <= TAG_LINE_MAX_LENGTH &&
|
||||
!isSubmitting;
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
|
||||
if (!canSubmit) {
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage(null);
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
const requestPayload = {
|
||||
gameName: trimmedGameName,
|
||||
matchCount: DEFAULT_MATCH_COUNT,
|
||||
platform: 'kr',
|
||||
tagLine: trimmedTagLine,
|
||||
} as const;
|
||||
const response = await requestAnalysis(requestPayload);
|
||||
|
||||
saveAnalysisRequest(response.jobId, requestPayload);
|
||||
navigate(`/analysis/${response.jobId}`);
|
||||
} catch (error) {
|
||||
setErrorMessage(getReadableErrorMessage(error));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="home-view" aria-labelledby="home-title">
|
||||
<div className="home-copy">
|
||||
<p className="eyebrow">Riot ID 기반 스타일 벡터</p>
|
||||
<h1 id="home-title">최근 솔로랭크에서 드러난 플레이 성향을 확인하세요.</h1>
|
||||
<p className="lead-copy">
|
||||
KR 서버 Riot ID를 입력하면 최근 랭크 게임을 분석해 지표별 강점,
|
||||
취약점, 주 챔피언 풀을 한 화면에 정리합니다.
|
||||
</p>
|
||||
<dl className="home-facts" aria-label="분석 기준">
|
||||
<div>
|
||||
<dt>Queue</dt>
|
||||
<dd>RANKED SOLO</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Sample</dt>
|
||||
<dd>최근 {DEFAULT_MATCH_COUNT}게임</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Region</dt>
|
||||
<dd>KR</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
<form className="analysis-form" onSubmit={handleSubmit}>
|
||||
<div className="form-header">
|
||||
<h2>분석 요청</h2>
|
||||
<span className="status-pill">API queued</span>
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<span>Game Name</span>
|
||||
<input
|
||||
autoComplete="off"
|
||||
maxLength={GAME_NAME_MAX_LENGTH}
|
||||
minLength={GAME_NAME_MIN_LENGTH}
|
||||
onChange={(event) => setGameName(event.target.value)}
|
||||
placeholder="Hide on bush"
|
||||
required
|
||||
value={gameName}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Tag Line</span>
|
||||
<input
|
||||
autoComplete="off"
|
||||
maxLength={TAG_LINE_MAX_LENGTH}
|
||||
minLength={TAG_LINE_MIN_LENGTH}
|
||||
onChange={(event) => setTagLine(event.target.value)}
|
||||
placeholder="KR1"
|
||||
required
|
||||
value={tagLine}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{errorMessage ? (
|
||||
<p className="message message-error" role="alert">
|
||||
{errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<button className="primary-action" disabled={!canSubmit} type="submit">
|
||||
{isSubmitting ? '요청 중' : '분석 시작'}
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
export function NotFoundPage() {
|
||||
return (
|
||||
<section className="empty-view" aria-labelledby="not-found-title">
|
||||
<p className="eyebrow">404</p>
|
||||
<h1 id="not-found-title">페이지를 찾을 수 없습니다.</h1>
|
||||
<p className="lead-copy">분석 요청 화면에서 다시 시작해 주세요.</p>
|
||||
<Link className="primary-action" to="/">
|
||||
홈으로 이동
|
||||
</Link>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import type { AnalysisJobStatusDto } from '@persona-lenz/shared';
|
||||
import {
|
||||
getAnalysisJob,
|
||||
getReadableErrorMessage,
|
||||
requestAnalysis,
|
||||
} from '../api/analysis';
|
||||
import {
|
||||
clearAnalysisRequest,
|
||||
loadAnalysisRequest,
|
||||
saveAnalysisRequest,
|
||||
} from '../lib/analysis-request-cache';
|
||||
import { getStageLabel } from '../lib/format';
|
||||
|
||||
const POLLING_INTERVAL_MS = 2_000;
|
||||
|
||||
export function ProgressPage() {
|
||||
const navigate = useNavigate();
|
||||
const { jobId } = useParams<{ jobId: string }>();
|
||||
const [job, setJob] = useState<AnalysisJobStatusDto | null>(null);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [isRetrying, setIsRetrying] = useState(false);
|
||||
const missingJobIdMessage = jobId ? null : '분석 작업 ID가 없습니다.';
|
||||
|
||||
useEffect(() => {
|
||||
if (!jobId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentJobId = jobId;
|
||||
let isActive = true;
|
||||
|
||||
async function pollJob() {
|
||||
try {
|
||||
const nextJob = await getAnalysisJob(currentJobId);
|
||||
|
||||
if (!isActive) {
|
||||
return;
|
||||
}
|
||||
|
||||
setJob(nextJob);
|
||||
setErrorMessage(null);
|
||||
|
||||
if (nextJob.status === 'completed') {
|
||||
if (nextJob.puuid) {
|
||||
clearAnalysisRequest(currentJobId);
|
||||
navigate(`/players/${nextJob.puuid}`, { replace: true });
|
||||
return;
|
||||
}
|
||||
|
||||
setErrorMessage('분석은 완료됐지만 결과 식별자를 받지 못했습니다.');
|
||||
window.clearInterval(intervalId);
|
||||
}
|
||||
|
||||
if (nextJob.status === 'failed') {
|
||||
window.clearInterval(intervalId);
|
||||
}
|
||||
} catch (error) {
|
||||
if (isActive) {
|
||||
setErrorMessage(getReadableErrorMessage(error));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const intervalId = window.setInterval(() => {
|
||||
void pollJob();
|
||||
}, POLLING_INTERVAL_MS);
|
||||
void pollJob();
|
||||
|
||||
return () => {
|
||||
isActive = false;
|
||||
window.clearInterval(intervalId);
|
||||
};
|
||||
}, [jobId, navigate]);
|
||||
|
||||
async function handleRetry() {
|
||||
if (!jobId) {
|
||||
navigate('/');
|
||||
return;
|
||||
}
|
||||
|
||||
const previousRequest = loadAnalysisRequest(jobId);
|
||||
|
||||
if (!previousRequest) {
|
||||
navigate('/');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRetrying(true);
|
||||
setErrorMessage(null);
|
||||
|
||||
try {
|
||||
const response = await requestAnalysis(previousRequest);
|
||||
|
||||
saveAnalysisRequest(response.jobId, previousRequest);
|
||||
navigate(`/analysis/${response.jobId}`, { replace: true });
|
||||
} catch (error) {
|
||||
setErrorMessage(getReadableErrorMessage(error));
|
||||
} finally {
|
||||
setIsRetrying(false);
|
||||
}
|
||||
}
|
||||
|
||||
const progressPercent = useMemo(() => {
|
||||
if (!job) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (job.status === 'completed') {
|
||||
return 100;
|
||||
}
|
||||
|
||||
if (job.progress.totalMatches <= 0) {
|
||||
return job.status === 'queued' ? 8 : 18;
|
||||
}
|
||||
|
||||
return Math.min(
|
||||
98,
|
||||
Math.round(
|
||||
(job.progress.fetchedMatches / job.progress.totalMatches) * 100,
|
||||
),
|
||||
);
|
||||
}, [job]);
|
||||
|
||||
return (
|
||||
<section className="progress-view" aria-labelledby="progress-title">
|
||||
<div className="progress-panel" aria-live="polite">
|
||||
<p className="eyebrow">Analysis job</p>
|
||||
<h1 id="progress-title">분석을 진행 중입니다.</h1>
|
||||
<p className="lead-copy">
|
||||
Riot API 응답과 매치 수에 따라 몇 분 정도 걸릴 수 있습니다.
|
||||
</p>
|
||||
|
||||
<div
|
||||
className="progress-meter"
|
||||
aria-label="분석 진행률"
|
||||
aria-valuemax={100}
|
||||
aria-valuemin={0}
|
||||
aria-valuenow={progressPercent}
|
||||
role="progressbar"
|
||||
>
|
||||
<span style={{ width: `${progressPercent}%` }} />
|
||||
</div>
|
||||
|
||||
<div className="progress-meta">
|
||||
<div>
|
||||
<span>Stage</span>
|
||||
<strong>{getStageLabel(job?.stage)}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Progress</span>
|
||||
<strong>{progressPercent}%</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Matches</span>
|
||||
<strong>
|
||||
{job
|
||||
? `${job.progress.fetchedMatches}/${job.progress.totalMatches}`
|
||||
: '-'}
|
||||
</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{job?.status === 'failed' ? (
|
||||
<p className="message message-error" role="alert">
|
||||
{job.error ?? '분석 작업이 실패했습니다.'}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{missingJobIdMessage || errorMessage ? (
|
||||
<p className="message message-error" role="alert">
|
||||
{missingJobIdMessage ?? errorMessage}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="action-row">
|
||||
{job?.status === 'failed' ? (
|
||||
<button
|
||||
className="primary-action"
|
||||
disabled={isRetrying}
|
||||
onClick={() => {
|
||||
void handleRetry();
|
||||
}}
|
||||
type="button"
|
||||
>
|
||||
{isRetrying ? '재시도 중' : '다시 시도'}
|
||||
</button>
|
||||
) : null}
|
||||
<Link className="secondary-action" to="/">
|
||||
새 요청 입력
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import * as React from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { Check, CircleAlert, LoaderCircle } from 'lucide-react'
|
||||
import type { AnalysisJobStatusDto } from '@persona-lenz/shared'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { getJobStatus, loadLastRequest, requestAnalysis, saveLastRequest } from '../lib/api'
|
||||
import { cn } from '../components/ui/utils'
|
||||
import { SiteFooter } from './site-footer'
|
||||
|
||||
const POLL_INTERVAL_MS = 2000
|
||||
|
||||
const STAGES = [
|
||||
{ id: 'resolve-account', label: '계정 확인' },
|
||||
{ id: 'fetch-match-ids', label: '랭크 게임 목록 조회' },
|
||||
{ id: 'fetch-match-details', label: '매치 데이터 수집' },
|
||||
{ id: 'extract-features', label: '플레이스타일 지표 추출' },
|
||||
{ id: 'build-profile', label: '프로필 생성' },
|
||||
] as const
|
||||
|
||||
function stageIndex(stage?: string): number {
|
||||
const index = STAGES.findIndex((entry) => entry.id === stage)
|
||||
return index < 0 ? 0 : index
|
||||
}
|
||||
|
||||
export function AnalysisProgressPage() {
|
||||
const { jobId } = useParams<{ jobId: string }>()
|
||||
const navigate = useNavigate()
|
||||
const [job, setJob] = React.useState<AnalysisJobStatusDto | null>(null)
|
||||
const [pollError, setPollError] = React.useState<string | null>(null)
|
||||
const [retrying, setRetrying] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!jobId) return
|
||||
let cancelled = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
async function poll() {
|
||||
try {
|
||||
const status = await getJobStatus(jobId!)
|
||||
if (cancelled) return
|
||||
setJob(status)
|
||||
setPollError(null)
|
||||
if (status.status === 'completed' && status.puuid) {
|
||||
timer = setTimeout(() => navigate(`/players/${status.puuid}`, { replace: true }), 600)
|
||||
return
|
||||
}
|
||||
if (status.status === 'failed') return
|
||||
} catch (cause) {
|
||||
if (cancelled) return
|
||||
setPollError(cause instanceof Error ? cause.message : '상태를 불러오지 못했어요.')
|
||||
}
|
||||
timer = setTimeout(poll, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
void poll()
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (timer) clearTimeout(timer)
|
||||
}
|
||||
}, [jobId, navigate])
|
||||
|
||||
async function handleRetry() {
|
||||
const lastRequest = loadLastRequest()
|
||||
if (!lastRequest) {
|
||||
navigate('/')
|
||||
return
|
||||
}
|
||||
setRetrying(true)
|
||||
try {
|
||||
const accepted = await requestAnalysis(lastRequest)
|
||||
saveLastRequest(lastRequest)
|
||||
navigate(`/analysis/${accepted.jobId}`, { replace: true })
|
||||
setJob(null)
|
||||
setRetrying(false)
|
||||
} catch (cause) {
|
||||
setPollError(cause instanceof Error ? cause.message : '재시도 요청에 실패했어요.')
|
||||
setRetrying(false)
|
||||
}
|
||||
}
|
||||
|
||||
const failed = job?.status === 'failed'
|
||||
const completed = job?.status === 'completed'
|
||||
const currentIndex = completed ? STAGES.length : stageIndex(job?.stage)
|
||||
const { fetchedMatches, totalMatches } = job?.progress ?? { fetchedMatches: 0, totalMatches: 0 }
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh flex flex-col bg-surface-page">
|
||||
<header className="px-6 py-5">
|
||||
<Link to="/" className="mx-auto flex w-full max-w-2xl items-center gap-2">
|
||||
<span aria-hidden className="size-2 rounded-full bg-brand" />
|
||||
<span className="text-[17px] font-bold text-text-primary">PersonaLenz</span>
|
||||
</Link>
|
||||
</header>
|
||||
|
||||
<main className="flex flex-1 items-center px-6 pb-16">
|
||||
<div className="mx-auto w-full max-w-xl">
|
||||
{failed ? (
|
||||
<div className="rounded-2xl border border-border bg-card p-8 shadow-[var(--shadow-card)]">
|
||||
<CircleAlert aria-hidden className="size-8 text-destructive" />
|
||||
<h1 className="mt-4 text-[22px] font-bold text-text-primary">분석을 끝내지 못했어요</h1>
|
||||
<p className="mt-2 text-[15px] leading-relaxed text-text-secondary">
|
||||
{job?.error ?? '알 수 없는 문제가 발생했어요. 잠시 후 다시 시도해 주세요.'}
|
||||
</p>
|
||||
<div className="mt-6 flex gap-3">
|
||||
<Button onClick={handleRetry} disabled={retrying} className="bg-brand text-white hover:bg-brand/90">
|
||||
{retrying ? '다시 요청하는 중…' : '다시 분석하기'}
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link to="/">홈으로</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-border bg-card p-8 shadow-[var(--shadow-card)]">
|
||||
<h1 className="text-[22px] font-bold text-text-primary">
|
||||
{completed ? '분석이 끝났어요!' : '플레이스타일을 분석하고 있어요'}
|
||||
</h1>
|
||||
<p className="mt-2 text-[15px] text-text-secondary">
|
||||
{completed
|
||||
? '대시보드로 이동합니다…'
|
||||
: '최근 랭크 게임을 수집해 지표를 계산하는 중이에요. 잠시만 기다려 주세요.'}
|
||||
</p>
|
||||
|
||||
<ol className="mt-8 space-y-5">
|
||||
{STAGES.map((stage, index) => {
|
||||
const isDone = index < currentIndex
|
||||
const isActive = index === currentIndex && !completed
|
||||
return (
|
||||
<li key={stage.id} className="flex items-center gap-4">
|
||||
<span
|
||||
className={cn(
|
||||
'flex size-8 shrink-0 items-center justify-center rounded-full border',
|
||||
isDone && 'border-brand bg-brand text-white',
|
||||
isActive && 'border-brand text-brand',
|
||||
!isDone && !isActive && 'border-border text-text-disabled',
|
||||
)}
|
||||
>
|
||||
{isDone ? (
|
||||
<Check aria-hidden className="size-4" />
|
||||
) : isActive ? (
|
||||
<LoaderCircle aria-hidden className="size-4 animate-spin" />
|
||||
) : (
|
||||
<span aria-hidden className="size-1.5 rounded-full bg-current" />
|
||||
)}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p
|
||||
className={cn(
|
||||
'text-[15px] font-medium',
|
||||
isDone || isActive ? 'text-text-primary' : 'text-text-tertiary',
|
||||
)}
|
||||
>
|
||||
{stage.label}
|
||||
</p>
|
||||
{stage.id === 'fetch-match-details' && isActive && totalMatches > 0 && (
|
||||
<div className="mt-2">
|
||||
<div
|
||||
role="progressbar"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={totalMatches}
|
||||
aria-valuenow={fetchedMatches}
|
||||
aria-label="매치 수집 진행률"
|
||||
className="h-1.5 w-full overflow-hidden rounded-full bg-surface-muted"
|
||||
>
|
||||
<div
|
||||
className="h-full rounded-full bg-brand transition-[width] duration-500"
|
||||
style={{ width: `${Math.round((fetchedMatches / totalMatches) * 100)}%` }}
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1.5 text-[13px] tabular-nums text-text-tertiary">
|
||||
{fetchedMatches} / {totalMatches} 게임
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
|
||||
{pollError && (
|
||||
<p role="alert" className="mt-6 text-[14px] text-destructive">
|
||||
{pollError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<SiteFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import * as React from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { Search } from 'lucide-react'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { Input } from '../components/ui/input'
|
||||
import { requestAnalysis, saveLastRequest } from '../lib/api'
|
||||
import { SiteFooter } from './site-footer'
|
||||
|
||||
function parseRiotId(raw: string): { gameName: string; tagLine: string } | null {
|
||||
const hashIndex = raw.lastIndexOf('#')
|
||||
if (hashIndex < 0) return null
|
||||
const gameName = raw.slice(0, hashIndex).trim()
|
||||
const tagLine = raw.slice(hashIndex + 1).trim()
|
||||
if (!gameName || !tagLine) return null
|
||||
return { gameName, tagLine }
|
||||
}
|
||||
|
||||
export function HomePage() {
|
||||
const navigate = useNavigate()
|
||||
const [riotId, setRiotId] = React.useState('')
|
||||
const [error, setError] = React.useState<string | null>(null)
|
||||
const [submitting, setSubmitting] = React.useState(false)
|
||||
|
||||
async function handleSubmit(event: React.FormEvent) {
|
||||
event.preventDefault()
|
||||
const parsed = parseRiotId(riotId)
|
||||
if (!parsed) {
|
||||
setError('게임이름#태그 형식으로 입력해 주세요. 예: Hide on bush#KR1')
|
||||
return
|
||||
}
|
||||
setError(null)
|
||||
setSubmitting(true)
|
||||
const payload = { ...parsed, platform: 'kr' as const, matchCount: 20 }
|
||||
try {
|
||||
const accepted = await requestAnalysis(payload)
|
||||
saveLastRequest(payload)
|
||||
navigate(`/analysis/${accepted.jobId}`)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '분석 요청에 실패했어요. 잠시 후 다시 시도해 주세요.')
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh flex flex-col bg-surface-page">
|
||||
<header className="px-6 py-5">
|
||||
<div className="mx-auto flex w-full max-w-2xl items-center gap-2">
|
||||
<span aria-hidden className="size-2 rounded-full bg-brand" />
|
||||
<span className="text-[17px] font-bold text-text-primary">PersonaLenz</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="flex flex-1 items-center px-6 pb-24">
|
||||
<div className="mx-auto w-full max-w-2xl">
|
||||
<h1 className="text-[32px] font-bold leading-snug tracking-[-0.01em] text-text-primary sm:text-[44px]">
|
||||
내 플레이스타일을
|
||||
<br />
|
||||
<span className="text-brand">벡터</span>로 읽는다
|
||||
</h1>
|
||||
<p className="mt-4 max-w-xl text-[16px] leading-relaxed text-text-secondary sm:text-[17px]">
|
||||
랭크 게임 기록으로 플레이스타일을 분석하고, 나와 비슷한 상위 티어
|
||||
플레이어와 비교해 다음 판에 시도할 개선점을 찾아드려요.
|
||||
</p>
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className="mt-10 rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]"
|
||||
>
|
||||
<label htmlFor="riot-id" className="text-[14px] font-medium text-text-secondary">
|
||||
Riot ID
|
||||
</label>
|
||||
<div className="mt-2 flex flex-col gap-3 sm:flex-row">
|
||||
<Input
|
||||
id="riot-id"
|
||||
value={riotId}
|
||||
onChange={(event) => setRiotId(event.target.value)}
|
||||
placeholder="Hide on bush#KR1"
|
||||
autoComplete="off"
|
||||
spellCheck={false}
|
||||
className="h-[52px] flex-1 text-[16px]"
|
||||
aria-invalid={error != null}
|
||||
aria-describedby={error ? 'riot-id-error' : undefined}
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
size="lg"
|
||||
disabled={submitting}
|
||||
className="bg-brand text-white hover:bg-brand/90 sm:w-auto"
|
||||
>
|
||||
<Search aria-hidden />
|
||||
{submitting ? '요청 보내는 중…' : '플레이스타일 분석하기'}
|
||||
</Button>
|
||||
</div>
|
||||
{error && (
|
||||
<p id="riot-id-error" role="alert" className="mt-3 text-[14px] text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-4 text-[14px] text-text-tertiary">
|
||||
최근 솔로랭크 20게임 기준 · 유사 플레이어 비교 · 챔피언 추천
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<SiteFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import * as React from 'react'
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom'
|
||||
import { CircleAlert, RefreshCw, SearchX, TriangleAlert } from 'lucide-react'
|
||||
import type { PlayerAnalysisDto, SimilarPlayersDto, TierInfoDto } from '@persona-lenz/shared'
|
||||
import { Button } from '../components/ui/button'
|
||||
import { Skeleton } from '../components/ui/skeleton'
|
||||
import { ChampionPoolCard } from '../components/dashboard/champion-pool-card'
|
||||
import { MetricDetailTabs } from '../components/dashboard/metric-detail-tabs'
|
||||
import { MetricHighlights } from '../components/dashboard/metric-highlights'
|
||||
import { PlaystyleRadar } from '../components/dashboard/playstyle-radar'
|
||||
import { SimilarPlayersSection } from '../components/dashboard/similar-players-section'
|
||||
import { ApiError, getLatestAnalysis, getSimilarPlayers, requestAnalysis, saveLastRequest } from '../lib/api'
|
||||
import { profileIconUrl, useChampionIndex } from '../lib/ddragon'
|
||||
import { ROLE_LABELS, computeCategoryScores, formatTier } from '../lib/metrics'
|
||||
import { SiteFooter } from './site-footer'
|
||||
|
||||
const SOLO_QUEUE = 'RANKED_SOLO_5x5'
|
||||
const LOW_SAMPLE_THRESHOLD = 5
|
||||
|
||||
function soloTier(tiers: TierInfoDto[]): TierInfoDto | undefined {
|
||||
return tiers.find((tier) => tier.queueType === SOLO_QUEUE) ?? tiers[0]
|
||||
}
|
||||
|
||||
function formatUpdatedAt(iso: string): string {
|
||||
return new Intl.DateTimeFormat('ko-KR', { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(iso))
|
||||
}
|
||||
|
||||
type LoadState =
|
||||
| { phase: 'loading' }
|
||||
| { phase: 'not-found' }
|
||||
| { phase: 'error'; message: string }
|
||||
| { phase: 'ready'; analysis: PlayerAnalysisDto; similar: SimilarPlayersDto | null }
|
||||
|
||||
export function PlayerDashboardPage() {
|
||||
const { puuid } = useParams<{ puuid: string }>()
|
||||
// puuid가 바뀌면 리마운트되어 로딩 상태부터 다시 시작
|
||||
return <PlayerDashboardContent key={puuid} puuid={puuid} />
|
||||
}
|
||||
|
||||
function PlayerDashboardContent({ puuid }: { puuid: string | undefined }) {
|
||||
const navigate = useNavigate()
|
||||
const champions = useChampionIndex()
|
||||
const [state, setState] = React.useState<LoadState>({ phase: 'loading' })
|
||||
const [reanalyzing, setReanalyzing] = React.useState(false)
|
||||
const [reanalyzeError, setReanalyzeError] = React.useState<string | null>(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!puuid) return
|
||||
let cancelled = false
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [analysis, similar] = await Promise.all([
|
||||
getLatestAnalysis(puuid!),
|
||||
getSimilarPlayers(puuid!).catch(() => null),
|
||||
])
|
||||
if (!cancelled) setState({ phase: 'ready', analysis, similar })
|
||||
} catch (cause) {
|
||||
if (cancelled) return
|
||||
if (cause instanceof ApiError && cause.status === 404) {
|
||||
setState({ phase: 'not-found' })
|
||||
} else {
|
||||
setState({
|
||||
phase: 'error',
|
||||
message: cause instanceof Error ? cause.message : '분석 결과를 불러오지 못했어요.',
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void load()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [puuid])
|
||||
|
||||
async function handleReanalyze() {
|
||||
if (state.phase !== 'ready') return
|
||||
const { gameName, tagLine } = state.analysis.account
|
||||
const payload = { gameName, tagLine, platform: 'kr' as const, matchCount: 20 }
|
||||
setReanalyzing(true)
|
||||
setReanalyzeError(null)
|
||||
try {
|
||||
const accepted = await requestAnalysis(payload)
|
||||
saveLastRequest(payload)
|
||||
navigate(`/analysis/${accepted.jobId}`)
|
||||
} catch (cause) {
|
||||
setReanalyzing(false)
|
||||
setReanalyzeError(cause instanceof Error ? cause.message : '재분석 요청에 실패했어요.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh flex flex-col bg-surface-page">
|
||||
<header className="border-b border-border px-6 py-4">
|
||||
<div className="mx-auto flex w-full max-w-5xl items-center justify-between">
|
||||
<Link to="/" className="flex items-center gap-2">
|
||||
<span aria-hidden className="size-2 rounded-full bg-brand" />
|
||||
<span className="text-[17px] font-bold text-text-primary">PersonaLenz</span>
|
||||
</Link>
|
||||
{state.phase === 'ready' && (
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="hidden text-[13px] text-text-tertiary sm:inline">
|
||||
{formatUpdatedAt(state.analysis.updatedAt)} 기준
|
||||
</span>
|
||||
<Button variant="outline" size="sm" onClick={handleReanalyze} disabled={reanalyzing}>
|
||||
<RefreshCw aria-hidden className={reanalyzing ? 'animate-spin' : undefined} />
|
||||
{reanalyzing ? '요청 중…' : '재분석'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="flex-1 px-6 py-8">
|
||||
<div className="mx-auto w-full max-w-5xl space-y-6">
|
||||
{reanalyzeError && (
|
||||
<p role="alert" className="rounded-xl bg-destructive-tint px-4 py-3 text-[14px] text-destructive">
|
||||
{reanalyzeError}
|
||||
</p>
|
||||
)}
|
||||
{state.phase === 'loading' && <DashboardSkeleton />}
|
||||
|
||||
{state.phase === 'not-found' && (
|
||||
<StatusCard
|
||||
icon={<SearchX aria-hidden className="size-8 text-text-disabled" />}
|
||||
title="아직 분석 결과가 없어요"
|
||||
description="분석할 랭크 게임이 없거나 분석이 완료되지 않았어요. 홈에서 Riot ID로 분석을 시작해 주세요."
|
||||
action={
|
||||
<Button asChild className="bg-brand text-white hover:bg-brand/90">
|
||||
<Link to="/">분석하러 가기</Link>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{state.phase === 'error' && (
|
||||
<StatusCard
|
||||
icon={<CircleAlert aria-hidden className="size-8 text-destructive" />}
|
||||
title="결과를 불러오지 못했어요"
|
||||
description={state.message}
|
||||
action={
|
||||
<Button variant="outline" onClick={() => navigate(0)}>
|
||||
다시 불러오기
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
|
||||
{state.phase === 'ready' && (
|
||||
<>
|
||||
<PlayerHero analysis={state.analysis} />
|
||||
<MetricHighlights strengths={state.analysis.strengths} weaknesses={state.analysis.weaknesses} />
|
||||
<SimilarPlayersSection players={state.similar?.matches ?? null} champions={champions} />
|
||||
<div className="grid items-start gap-6 lg:grid-cols-[340px_minmax(0,1fr)]">
|
||||
<ChampionPoolCard championPool={state.analysis.profile.championPool} champions={champions} />
|
||||
<MetricDetailTabs playstyle={state.analysis.profile.playstyle} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<SiteFooter />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function PlayerHero({ analysis }: { analysis: PlayerAnalysisDto }) {
|
||||
const champions = useChampionIndex()
|
||||
const { account, profile } = analysis
|
||||
const tier = soloTier(account.tiers)
|
||||
const tierLabel = formatTier(tier?.tier, tier?.rank)
|
||||
const totalGames = tier ? tier.wins + tier.losses : 0
|
||||
const winRate = tier && totalGames > 0 ? Math.round((tier.wins / totalGames) * 100) : null
|
||||
const lowSample = profile.sampleGameCount < LOW_SAMPLE_THRESHOLD
|
||||
const categoryScores = computeCategoryScores(profile.playstyle)
|
||||
|
||||
return (
|
||||
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)] sm:p-8">
|
||||
<div className="grid gap-8 lg:grid-cols-[minmax(0,1fr)_380px]">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-4">
|
||||
{champions ? (
|
||||
<img
|
||||
src={profileIconUrl(champions.version, account.profileIconId)}
|
||||
alt=""
|
||||
className="size-16 rounded-2xl"
|
||||
/>
|
||||
) : (
|
||||
<span aria-hidden className="size-16 rounded-2xl bg-surface-muted" />
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<h1 className="truncate text-[24px] font-bold tracking-[-0.01em] text-text-primary">
|
||||
{account.gameName}
|
||||
<span className="ms-1 font-medium text-text-tertiary">#{account.tagLine}</span>
|
||||
</h1>
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-2">
|
||||
{tierLabel && (
|
||||
<span className="rounded-md bg-surface-subtle px-2 py-0.5 text-[13px] font-bold text-text-secondary">
|
||||
{tierLabel} · {tier!.leaguePoints}LP
|
||||
</span>
|
||||
)}
|
||||
{winRate != null && (
|
||||
<span className="text-[13px] tabular-nums text-text-secondary">
|
||||
{totalGames}전 승률 {winRate}%
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dl className="mt-8 grid grid-cols-3 gap-4">
|
||||
<div>
|
||||
<dt className="text-[13px] text-text-tertiary">주 포지션</dt>
|
||||
<dd className="mt-1 text-[22px] font-bold text-text-primary">{ROLE_LABELS[profile.mainRole]}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-[13px] text-text-tertiary">분석 게임</dt>
|
||||
<dd className="mt-1 text-[22px] font-bold tabular-nums text-text-primary">
|
||||
{profile.sampleGameCount}
|
||||
<span className="ms-0.5 text-[13px] font-medium text-text-tertiary">게임</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-[13px] text-text-tertiary">신뢰도</dt>
|
||||
<dd className="mt-1 text-[22px] font-bold tabular-nums text-text-primary">
|
||||
{Math.round(profile.confidence * 100)}
|
||||
<span className="ms-0.5 text-[13px] font-medium text-text-tertiary">%</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{lowSample && (
|
||||
<p className="mt-6 flex items-start gap-2 rounded-xl bg-warning-tint p-4 text-[14px] leading-relaxed text-text-secondary">
|
||||
<TriangleAlert aria-hidden className="mt-0.5 size-4 shrink-0 text-warning" />
|
||||
표본이 {profile.sampleGameCount}게임뿐이라 결과가 흔들릴 수 있어요. 랭크 게임을 더 플레이한 뒤
|
||||
재분석하면 정확해져요.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<PlaystyleRadar scores={categoryScores} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
|
||||
function StatusCard({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
action,
|
||||
}: {
|
||||
icon: React.ReactNode
|
||||
title: string
|
||||
description: string
|
||||
action: React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<div className="mx-auto max-w-xl rounded-2xl border border-border bg-card p-8 text-center shadow-[var(--shadow-card)]">
|
||||
<div className="flex justify-center">{icon}</div>
|
||||
<h1 className="mt-4 text-[22px] font-bold text-text-primary">{title}</h1>
|
||||
<p className="mt-2 text-[15px] leading-relaxed text-text-secondary">{description}</p>
|
||||
<div className="mt-6 flex justify-center">{action}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DashboardSkeleton() {
|
||||
return (
|
||||
<>
|
||||
<Skeleton className="h-[380px] w-full rounded-2xl" />
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<Skeleton className="h-[280px] rounded-2xl" />
|
||||
<Skeleton className="h-[280px] rounded-2xl" />
|
||||
</div>
|
||||
<Skeleton className="h-[240px] w-full rounded-2xl" />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export function SiteFooter() {
|
||||
return (
|
||||
<footer className="border-t border-border px-6 py-6">
|
||||
<p className="mx-auto max-w-2xl text-[13px] leading-relaxed text-text-tertiary">
|
||||
persona-lenz is not endorsed by Riot Games and does not reflect the views or
|
||||
opinions of Riot Games or anyone officially involved in producing or managing
|
||||
Riot Games properties. Riot Games and all associated properties are trademarks
|
||||
or registered trademarks of Riot Games, Inc.
|
||||
</p>
|
||||
</footer>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* StyleSeed — Formatting Utilities
|
||||
* Number, date, and trend formatters.
|
||||
* Includes Korean (KRW) formatters and generic currency/locale support.
|
||||
*/
|
||||
|
||||
// ── Currency Formatting ──────────────────────────────
|
||||
|
||||
/** Korean Won abbreviated format (3,500원 / 1,870만원 / 3.8억원 / 1.2조원) */
|
||||
export function formatKRW(value: number): string {
|
||||
const abs = Math.abs(value)
|
||||
const sign = value < 0 ? "-" : ""
|
||||
|
||||
if (abs >= 1_000_000_000_000) {
|
||||
return `${sign}${(abs / 1_000_000_000_000).toFixed(1)}조원`
|
||||
}
|
||||
if (abs >= 100_000_000) {
|
||||
return `${sign}${(abs / 100_000_000).toFixed(1)}억원`
|
||||
}
|
||||
if (abs >= 10_000) {
|
||||
return `${sign}${Math.round(abs / 10_000).toLocaleString()}만원`
|
||||
}
|
||||
return `${sign}${abs.toLocaleString()}원`
|
||||
}
|
||||
|
||||
/** Split number and unit for JSX (big number + small unit pattern) */
|
||||
export function splitNumberUnit(value: number): { number: string; unit: string } {
|
||||
const abs = Math.abs(value)
|
||||
const sign = value < 0 ? "-" : ""
|
||||
|
||||
if (abs >= 1_000_000_000_000) {
|
||||
return { number: `${sign}${(abs / 1_000_000_000_000).toFixed(1)}`, unit: "조원" }
|
||||
}
|
||||
if (abs >= 100_000_000) {
|
||||
return { number: `${sign}${(abs / 100_000_000).toFixed(1)}`, unit: "억원" }
|
||||
}
|
||||
if (abs >= 10_000) {
|
||||
return { number: `${sign}${Math.round(abs / 10_000).toLocaleString()}`, unit: "만원" }
|
||||
}
|
||||
return { number: `${sign}${abs.toLocaleString()}`, unit: "원" }
|
||||
}
|
||||
|
||||
/** Thousand separator formatting (1,870 / 3,500) */
|
||||
export function formatNumber(value: number, decimals = 0): string {
|
||||
return value.toLocaleString("ko-KR", {
|
||||
minimumFractionDigits: decimals,
|
||||
maximumFractionDigits: decimals,
|
||||
})
|
||||
}
|
||||
|
||||
/** Generic currency formatter (locale-aware) */
|
||||
export function formatCurrency(value: number, locale = "en-US", currency = "USD"): string {
|
||||
return new Intl.NumberFormat(locale, { style: "currency", currency, maximumFractionDigits: 0 }).format(value)
|
||||
}
|
||||
|
||||
// ── Percent & Trend ──────────────────────────────────
|
||||
|
||||
/** Trend percent (+12.4% / -3.2%) */
|
||||
export function formatPercent(value: number, decimals = 1): string {
|
||||
const prefix = value > 0 ? "+" : ""
|
||||
return `${prefix}${value.toFixed(decimals)}%`
|
||||
}
|
||||
|
||||
/** Trend direction */
|
||||
export function getTrendDirection(value: number): "up" | "down" | "neutral" {
|
||||
if (value > 0) return "up"
|
||||
if (value < 0) return "down"
|
||||
return "neutral"
|
||||
}
|
||||
|
||||
// ── Date Formatting ──────────────────────────────────
|
||||
|
||||
/** Korean date format (2026년 3월 27일 금요일) */
|
||||
export function formatDateKR(date: Date): string {
|
||||
const weekdays = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"]
|
||||
const y = date.getFullYear()
|
||||
const m = date.getMonth() + 1
|
||||
const d = date.getDate()
|
||||
const w = weekdays[date.getDay()]
|
||||
return `${y}년 ${m}월 ${d}일 ${w}`
|
||||
}
|
||||
|
||||
/** Generic date format (locale-aware) */
|
||||
export function formatDate(date: Date, locale = "en-US"): string {
|
||||
return date.toLocaleDateString(locale, { year: "numeric", month: "long", day: "numeric", weekday: "long" })
|
||||
}
|
||||
|
||||
/** Chart axis date (03/20) */
|
||||
export function formatDateShort(date: Date): string {
|
||||
const m = String(date.getMonth() + 1).padStart(2, "0")
|
||||
const d = String(date.getDate()).padStart(2, "0")
|
||||
return `${m}/${d}`
|
||||
}
|
||||
|
||||
/** Relative time (just now, 3m ago, 2h ago, yesterday, Mar 20) */
|
||||
export function formatRelativeTime(date: Date, locale: "ko" | "en" = "en"): string {
|
||||
const now = new Date()
|
||||
const diff = now.getTime() - date.getTime()
|
||||
const minutes = Math.floor(diff / 60_000)
|
||||
const hours = Math.floor(diff / 3_600_000)
|
||||
const days = Math.floor(diff / 86_400_000)
|
||||
|
||||
if (locale === "ko") {
|
||||
if (minutes < 1) return "방금 전"
|
||||
if (minutes < 60) return `${minutes}분 전`
|
||||
if (hours < 24) return `${hours}시간 전`
|
||||
if (days === 1) return "어제"
|
||||
if (days < 7) return `${days}일 전`
|
||||
return `${date.getMonth() + 1}월 ${date.getDate()}일`
|
||||
}
|
||||
|
||||
if (minutes < 1) return "just now"
|
||||
if (minutes < 60) return `${minutes}m ago`
|
||||
if (hours < 24) return `${hours}h ago`
|
||||
if (days === 1) return "yesterday"
|
||||
if (days < 7) return `${days}d ago`
|
||||
return date.toLocaleDateString("en-US", { month: "short", day: "numeric" })
|
||||
}
|
||||
|
||||
/** Date range (3/20 ~ 3/27) */
|
||||
export function formatDateRange(start: Date, end: Date): string {
|
||||
return `${start.getMonth() + 1}/${start.getDate()} ~ ${end.getMonth() + 1}/${end.getDate()}`
|
||||
}
|
||||
@@ -3,6 +3,10 @@
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"],
|
||||
"@styleseed/motion": ["./src/motion"]
|
||||
},
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user