Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions packages/kivex-react-native/generator/IconTemplate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export function generateIconCode(svgChildren: string, componentName: string): string {
return `import { forwardRef } from 'react';
import { IconBase } from '../components/IconBase';
import type { IconProps } from '../types/IconProps';

export const ${componentName} = forwardRef<SVGSVGElement, IconProps>(
(
{

size = 24,
color = 'currentColor',
strokeWidth = 2,
...props
},
ref
) => {
return (
<IconBase
ref={ref}
size={size}
color={color}
strokeWidth={strokeWidth}
{...props}
>
${svgChildren}
</IconBase>
);
}
);

${componentName}.displayName = '${componentName}';`;
}
128 changes: 128 additions & 0 deletions packages/kivex-react-native/generator/build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
import path from 'path';
import { fileURLToPath } from 'url';
import fg from 'fast-glob';
import fs from 'fs-extra';
import { transform } from '@svgr/core';
import { generateIconCode } from './IconTemplate';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

export async function writeFileIfChanged(
filePath: string,
newContent: string,
force: boolean
): Promise<boolean> {
const exists = await fs.pathExists(filePath);
if (!exists) {
await fs.writeFile(filePath, newContent, 'utf8');
return true;
}
const currentContent = await fs.readFile(filePath, 'utf8');
if (force || currentContent !== newContent) {
await fs.writeFile(filePath, newContent, 'utf8');
return true;
}
return false;
}

function extractSvgChildren(componentCode: string): string {
const match = componentCode.match(/<svg[^>]*>([\s\S]*?)<\/svg>/);
if (!match) {
throw new Error('Could not find SVG element in generated code.');
}
return match[1].trim();
}

export async function generateIcons(options?: { force?: boolean }): Promise<void> {
const force = options?.force ?? process.argv.includes('--force');

const ROOT_DIRECTORY = path.resolve(__dirname, '..');
const ICONS_DIRECTORY = path.join(ROOT_DIRECTORY, '../../icons');
const OUTPUT_DIRECTORY = path.join(ROOT_DIRECTORY, 'src', 'icons');

await fs.ensureDir(OUTPUT_DIRECTORY);

const svgFiles = await fg('**/*.svg', {
cwd: ICONS_DIRECTORY,
absolute: true,
});

if (svgFiles.length === 0) {
console.warn('⚠️ No SVG files found in', ICONS_DIRECTORY);
return;
}

const generatedComponents: string[] = [];
const exportStatements: string[] = [];

for (const filePath of svgFiles) {
const svgContent = await fs.readFile(filePath, 'utf8');
const fileName = path.basename(filePath, '.svg');
const componentName = fileName
.replace(/[-_](.)/g, (_, char) => char.toUpperCase())
.replace(/^./, (char) => char.toUpperCase());

const svgrResult = await transform(
svgContent,
{
typescript: true,
jsxRuntime: 'automatic',
exportType: 'default',
plugins: ['@svgr/plugin-jsx'],
expandProps: false,
dimensions: false,
svgProps: {},
},
{ componentName }
);

const childrenJsx = extractSvgChildren(svgrResult);
const finalCode = generateIconCode(childrenJsx, componentName);

const outputFile = path.join(OUTPUT_DIRECTORY, `${fileName}.tsx`);
const written = await writeFileIfChanged(outputFile, finalCode, force);
if (written) {
console.log(`✅ Generated/updated ${fileName}.tsx`);
} else {
console.log(`⏩ Skipped ${fileName}.tsx (unchanged)`);
}

generatedComponents.push(fileName);
exportStatements.push(`export { ${componentName} } from './icons/${fileName}';`);
}

// Remove orphaned component files
const existingFiles = await fs.readdir(OUTPUT_DIRECTORY);
for (const file of existingFiles) {
if (file === 'index.ts') continue;
if (!file.endsWith('.tsx')) continue;
const baseName = path.basename(file, '.tsx');
if (!generatedComponents.includes(baseName)) {
const filePath = path.join(OUTPUT_DIRECTORY, file);
await fs.remove(filePath);
console.log(`🗑️ Removed orphaned ${file}`);
}
}

const mainIndexContent =
`export type { IconProps } from './types/IconProps';\n` +
exportStatements.join('\n') +
'\n';

const mainIndexPath = path.join(ROOT_DIRECTORY, 'src', 'index.ts');
const written = await writeFileIfChanged(mainIndexPath, mainIndexContent, force);
if (written) {
console.log(`📦 Main entry updated at ${mainIndexPath}`);
} else {
console.log(`⏩ Skipped ${mainIndexPath} (unchanged)`);
}
}

// Reliable: compare actual file paths
if (process.argv[1] === __filename) {
generateIcons().catch((err) => {
console.error('❌ Error:', err);
process.exit(1);
});
}
70 changes: 70 additions & 0 deletions packages/kivex-react-native/generator/watch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import path from 'path';
import { fileURLToPath } from 'url';
import { generateIcons } from './build';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Correct path: root icons folder (three levels up from generator)
const ICONS_DIRECTORY = path.join(__dirname, '../../../icons');

async function watch() {
let chokidar;
try {
chokidar = await import('chokidar');
console.log('✅ chokidar loaded successfully');
} catch (err) {
console.error('❌ Failed to load chokidar. Please install it:', err);
process.exit(1);
}

// Initial generation
await generateIcons();

console.log(`👀 Watching ${ICONS_DIRECTORY} for changes...`);
console.log(' Press Ctrl+C to stop.');

let timeout: NodeJS.Timeout | null = null;
let isRunning = false;

const watcher = chokidar.watch(ICONS_DIRECTORY, {
persistent: true,
ignoreInitial: true,
depth: 10,
});

watcher.on('all', (event, filePath) => {
if (!filePath.endsWith('.svg')) return;

if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
if (isRunning) return;
isRunning = true;
console.log(`\n🔄 Change detected (${event}), regenerating...`);
generateIcons()
.catch((err) => console.error('❌ Error during regeneration:', err))
.finally(() => {
isRunning = false;
timeout = null;
});
}, 200);
});

process.on('SIGINT', () => {
console.log('\n👋 Stopping watch...');
watcher.close();
process.exit(0);
});

watcher.on('ready', () => {
console.log('✅ Watcher is ready and monitoring for changes.');
});
}

// Only run when executed directly
if (process.argv[1] === __filename) {
watch().catch((err) => {
console.error('❌ Error in watch:', err);
process.exit(1);
});
}
36 changes: 36 additions & 0 deletions packages/kivex-react-native/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "kivex-react-native",
"version": "0.0.1",
"description": "Kivex icon library for React Native",
"main": "src/index.ts",
"types": "src/index.ts",
"scripts": {
"generate": "tsx generator/build.ts",
"watch": "tsx generator/watch.ts"
},
"peerDependencies": {
"react": ">=17.0.0",
"react-native": ">=0.64.0"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/node": "^20.11.0",
"chokidar": "^3.6.0",
"fast-glob": "^3.3.2",
"fs-extra": "^11.2.0",
"ts-node": "^10.9.2",
"tsx": "^4.23.1",
"typescript": "^5.3.3"
},
"files": [
"src"
],
"keywords": [
"react-native",
"icons",
"svg",
"kivex"
],
"license": "MIT",
"type": "module"
}
38 changes: 38 additions & 0 deletions packages/kivex-react-native/src/components/IconBase.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { ReactNode } from 'react';
import { forwardRef } from 'react';
import type { IconProps } from '../types/IconProps';

interface IconBaseProps extends IconProps {
children: ReactNode;
}

export const IconBase = forwardRef<SVGSVGElement, IconBaseProps>(
(
{
size = 24,
color = 'currentColor',
strokeWidth = 2,
children,
...props
},
ref
) => {
return (
<svg
ref={ref}
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth={strokeWidth}
strokeLinecap='round'
strokeLinejoin='round'
{...props}
>
{children}
</svg>
)});

IconBase.displayName = 'IconBase';
30 changes: 30 additions & 0 deletions packages/kivex-react-native/src/icons/alert.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { forwardRef } from 'react';
import { IconBase } from '../components/IconBase';
import type { IconProps } from '../types/IconProps';

export const Alert = forwardRef<SVGSVGElement, IconProps>(
(
{

size = 24,
color = 'currentColor',
strokeWidth = 2,
...props
},
ref
) => {
return (
<IconBase
ref={ref}
size={size}
color={color}
strokeWidth={strokeWidth}
{...props}
>
<circle cx={12} cy={12} r={10} /><path d="M12 8v5" /><circle cx={12} cy={16} r={0.5} />
</IconBase>
);
}
);

Alert.displayName = 'Alert';
30 changes: 30 additions & 0 deletions packages/kivex-react-native/src/icons/angry.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { forwardRef } from 'react';
import { IconBase } from '../components/IconBase';
import type { IconProps } from '../types/IconProps';

export const Angry = forwardRef<SVGSVGElement, IconProps>(
(
{

size = 24,
color = 'currentColor',
strokeWidth = 2,
...props
},
ref
) => {
return (
<IconBase
ref={ref}
size={size}
color={color}
strokeWidth={strokeWidth}
{...props}
>
<path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10Z" /><path d="M8 10.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1Z" /><path d="M16 10.5a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1Z" /><path d="M8 16c1.769-3.095 6.231-3.095 8 0" /><path d="m7 7 2 1" /><path d="m15 8 2-1" />
</IconBase>
);
}
);

Angry.displayName = 'Angry';
Loading