Skip to content

Commit

Permalink
feat: add esbuild template
Browse files Browse the repository at this point in the history
  • Loading branch information
b-ma committed Jun 12, 2024
1 parent a13a883 commit 3418974
Show file tree
Hide file tree
Showing 19 changed files with 173 additions and 11 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
.Thumb.db

node_modules
templates/esbuild/build
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ Interactive command line tools for scaffolding simple Web Audio test apps and de
npx @ircam/create@latest [dirname]
```

## TODOS

- [ ] add `--template=nobuild` option on command line to simplify tutorial updates

## Credits

[https://soundworks.dev/credits.html](https://soundworks.dev/credits.html)
Expand Down
59 changes: 48 additions & 11 deletions create.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env node

import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import * as url from 'node:url';

import chalk from 'chalk';
import { program } from 'commander';
import { mkdirp } from 'mkdirp';
import prompts from 'prompts';
import readdir from 'recursive-readdir';
Expand All @@ -24,9 +23,24 @@ export function toValidPackageName(name) {

console.log(`${chalk.gray(`[@ircam/create#v${version}]`)}`);

const templates = ['nobuild', 'esbuild'];

program
.argument('[path]', 'Directory in which we should create the project')
.option('-t, --template <string>', 'Template to use');

program.parse();

let { template } = program.opts();

if (template && !templates.includes(template)) {
console.log(chalk.red(`> Invalid template "${template}", valid templates are: "${templates.join('", "')}", aborting...`));
process.exit(1);
}

let targetDir;
if (process.argv[2]) {
targetDir = process.argv[2];
if (program.processedArgs[0]) {
targetDir = program.processedArgs[0];
} else {
targetDir = '.';
}
Expand All @@ -53,16 +67,32 @@ if (fs.existsSync(targetWorkingDir) && fs.readdirSync(targetWorkingDir).length >
process.exit(1);
}

const templateDir = path.join(__dirname, 'templates', 'simple-online');
if (!template) {
const result = await prompts([
{
type: 'select',
name: 'template',
message: 'Pick a template',
choices: templates.map(value => {
return { value };
}),
}
]);

template = result.template;
}

const templateDir = path.join(__dirname, 'templates', template);

const ignoreFiles = ['.DS_Store', 'Thumbs.db'];
const files = await readdir(templateDir, ignoreFiles);

await mkdirp(targetWorkingDir);


console.log('');
console.log(`> scaffolding app in:`, targetWorkingDir);
console.log(`> template:`, template);
console.log('');

for (let src of files) {
const file = path.relative(templateDir, src);
Expand All @@ -73,14 +103,15 @@ for (let src of files) {
switch (file) {
case 'package.json': {
const pkg = JSON.parse(fs.readFileSync(src));
pkg.name = toValidPackageName(options.name);
pkg.name = toValidPackageName(targetDir);

fs.writeFileSync(dest, JSON.stringify(pkg, null, 2));
break;
}
case 'README.md':
case 'index.html':
case 'main.js': {
case 'main.js':
case 'src/index.js': {
let content = fs.readFileSync(src).toString();
content = content.replace(/\[app_name\]/mg, targetDir);
fs.writeFileSync(dest, content);
Expand All @@ -95,17 +126,23 @@ for (let src of files) {
}

console.log(chalk.yellow('> your project is ready!'));

console.log('')
console.log(chalk.yellow('> next steps:'));

let i = 1;

const relative = path.relative(process.cwd(), targetWorkingDir);
if (relative !== '') {
console.log(` ${i++}: ${chalk.cyan(`cd ${relative}`)}`);
}

console.log(` ${i++}: ${chalk.cyan('npx serve')}`);
if (template === 'nobuild') {
console.log(` ${i++}: ${chalk.cyan('npx serve')}`);
console.log('');
} else if (template === 'esbuild') {
console.log(` ${i++}: ${chalk.cyan('npm install')}`);
console.log(` ${i++}: ${chalk.cyan('npm run dev')}`);
console.log('');
}

console.log('')
console.log(`- to close the dev server, press ${chalk.bold(chalk.cyan('Ctrl-C'))}`);
2 changes: 2 additions & 0 deletions templates/esbuild/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
package-lock=false

File renamed without changes.
File renamed without changes.
13 changes: 13 additions & 0 deletions templates/esbuild/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>[app_name]</title>
<script type="module" defer src="./build/index.js"></script>
<link rel="stylesheet" type="text/css" href="./styles.css" />
</head>
<body>

</body>
</html>
File renamed without changes.
14 changes: 14 additions & 0 deletions templates/esbuild/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"scripts": {
"dev": "concurrently \"esbuild src/index.js --bundle --format=esm --watch --outdir=build\" \"serve\""
},
"devDependencies": {
"concurrently": "^8.2.2",
"esbuild": "^0.21.5",
"serve": "^14.2.3"
},
"dependencies": {
"@ircam/sc-components": "^3.0.0-alpha.61",
"lit": "^3.1.4"
}
}
23 changes: 23 additions & 0 deletions templates/esbuild/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { html, render } from 'lit';
import '@ircam/sc-components';

import resumeAudioContext from '../lib/resume-audio-context.js';
import loadAudioBuffer from '../lib/load-audio-buffer.js';

const audioContext = new AudioContext();
await resumeAudioContext(audioContext);

const buffer = await loadAudioBuffer('./assets/sample.wav', audioContext.sampleRate);

render(html`
<h1>[app_name]</h1>
<sc-bang
@input=${e => {
const src = audioContext.createBufferSource();
src.connect(audioContext.destination);
src.buffer = buffer;
src.start();
}}
></sc-bang>
`, document.body);

File renamed without changes.
10 changes: 10 additions & 0 deletions templates/nobuild/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# [app_name]

Simple template for Web Audio demos and tests

## Usage

```
cd path/to/dir
npx serve
```
Binary file added templates/nobuild/assets/sample.wav
Binary file not shown.
File renamed without changes.
16 changes: 16 additions & 0 deletions templates/nobuild/lib/load-audio-buffer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const contexts = new Map();

export default async function loadAudioBuffer(pathname, sampleRate = 48000) {
if (!contexts.has(sampleRate)) {
const context = new OfflineAudioContext(1, 1, sampleRate);
contexts.set(sampleRate, context);
}

const response = await fetch(pathname);
const arrayBuffer = await response.arrayBuffer();

const context = contexts.get(sampleRate);
const audioBuffer = await context.decodeAudioData(arrayBuffer);

return audioBuffer;
}
15 changes: 15 additions & 0 deletions templates/nobuild/lib/resume-audio-context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { html, render } from 'https://unpkg.com/lit-html';

export default async function resumeAudioContext(audioContext) {
return new Promise(resolve => {
render(html`
<sc-button
style="position: absolute; top: 0; left: 0; width: 100vw; height: 100vh; font-size: 14px;"
@release=${async () => {
await audioContext.resume();
resolve();
}}
>Resume context</sc-button>
`, document.body);
});
}
File renamed without changes.
27 changes: 27 additions & 0 deletions templates/nobuild/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
:root {
--background-color: #181817;
--font-color: #ffffff;
--font-family: Consolas, monaco, monospace;
--font-size: 62.5%; // such that 1rem == 10px
}

* {
box-sizing: border-box;
font-family: var(--font-family);
}

html, body {
width: 100%;
min-height: 100vh;
background-color: var(--background-color);
color: var(--font-color);
}

html {
font-size: var(--font-size);
}

body {
padding: 20px;
margin: 0;
}

0 comments on commit 3418974

Please sign in to comment.