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
33 changes: 31 additions & 2 deletions docs/commands/create-app.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,36 @@ You can run `pnpm create @dhis2/app@alpha --help` for the list of options availa
new app (TypeScript, pnpm, basic
template) [boolean] [default: false]
--typescript, --ts, --typeScript Use TypeScript or JS [boolean]
--template Which template to use (Basic, With
React Router, or GitHub
--template Which template to use (basic,
react-router, plugin, or GitHub
template specifier) [string]
--pluginType, --plugin-type Which kind of plugin to scaffold
when using the plugin template
(implies --template plugin)
[string] [choices: "form-field", "enrollment", "bulk-data-entry", "dashboard"]
--packageManager, --package, Package Manager
--packagemanager [string]
```

## Plugin template

`--template plugin` scaffolds a [DHIS2 plugin](https://developers.dhis2.org/docs/plugins/general-plugin-guide/) in TypeScript. Pick the kind of plugin with `--pluginType`. You are prompted for it if you don't pass it, and it is required when using `--yes`:

| `--pluginType` | Host app | `pluginType` in `d2.config.js` |
| ----------------- | -------------------------------------------- | ------------------------------ |
| `form-field` | Capture: a field in an event/enrollment form | `CAPTURE_FORM_FIELD` |
| `enrollment` | Capture: enrollment dashboard / event pages | `CAPTURE_ENROLLMENT` |
| `bulk-data-entry` | Bulk data entry from working lists | `TRACKER_BULK_DATA_ENTRY` |
| `dashboard` | Dashboard app: a dashboard item | `DASHBOARD` |

The generated project contains:

- `src/Plugin.tsx`: the plugin component, exposed as the `plugin` entry point
- `src/types/plugin.ts`: TypeScript types for the props the host app passes
- `src/App.tsx`: a local development harness that renders the plugin with mocked props, so `pnpm start` works without a host app. Remove `entryPoints.app` from `d2.config.js` before release if you don't want it installed as an app.

The Capture app does not read `pluginType`; the other values are a naming convention that describes the plugin in `/api/apps` and the App Hub. Dashboard plugins must use `DASHBOARD`.

## Community templates

The CLI also supports installing templates developed by the community using a GitHub repository URL or `owner/repo` specifier. These templates are maintained outside the CLI, so you should review the source code before using them in your project.
Expand Down Expand Up @@ -81,6 +104,12 @@ pnpm create @dhis2/app my-app --yes
# use the default settings but override the template
pnpm create @dhis2/app my-app --yes --template react-router

# scaffold a Capture form field plugin
pnpm create @dhis2/app my-plugin --template plugin --pluginType form-field

# scaffold a Dashboard plugin with the other defaults (--pluginType implies --template plugin)
pnpm create @dhis2/app my-plugin --yes --pluginType dashboard

# use a custom template from GitHub (owner/repo)
pnpm create @dhis2/app my-app --template owner/repo

Expand Down
8 changes: 8 additions & 0 deletions packages/create-app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,11 @@ By passing `--yes` argument, this will create a new DHIS2 web application using
If you omit the `--yes` argument `pnpm create @dhis2/app project-name` then you will be prompted and guided through a wizard to choose your options.

You can run the commands in `debug` mode to get more verbose logs by passing the `--debug` option (`pnpm create @dhis2/app project-name --debug`).

To scaffold a DHIS2 plugin (Capture form field, enrollment, bulk data entry, or Dashboard) instead of an app, use the plugin template:

```sh
pnpm create @dhis2/app my-plugin --template plugin --pluginType form-field
```

See the [create-app docs](../../docs/commands/create-app.md) for all options and templates.
82 changes: 77 additions & 5 deletions packages/create-app/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ const { input, select } = require('@inquirer/prompts')
const fg = require('fast-glob')
const fs = require('fs-extra')
const { default: getPackageManager } = require('./utils/getPackageManager')
const {
pluginBaseTemplateDirectory,
pluginTypes,
pluginTypeValues,
getPluginOverlayDirectory,
resolvePluginOptions,
assertPluginTypeChosen,
} = require('./utils/pluginTemplates')
const resolveExternalTemplateSource = require('./utils/resolveExternalTemplateSource')

process.on('uncaughtException', (error) => {
Expand Down Expand Up @@ -47,9 +55,16 @@ const commandHandler = {
},
template: {
description:
'Which template to use (Basic, With React Router, or GitHub template specifier)',
'Which template to use (basic, react-router, plugin, or GitHub template specifier)',
type: 'string',
},
pluginType: {
description:
'Which kind of plugin to scaffold (implies --template plugin). Required with --template plugin when using --yes',
type: 'string',
choices: pluginTypeValues,
alias: ['plugin-type', 'plugintype'],
},
packageManager: {
description: 'Package Manager',
type: 'string',
Expand All @@ -67,6 +82,10 @@ const getBuiltInTemplateDirectory = (templateName) => {
return templates.templateWithReactRouter
}

if (templateName === 'plugin') {
return pluginBaseTemplateDirectory
}

return null
}

Expand All @@ -90,11 +109,23 @@ const command = {
reporter.log(`name of project: ${name}`)
}

let resolvedPluginOptions
try {
resolvedPluginOptions = resolvePluginOptions({
template: argv.template,
pluginType: argv.pluginType,
})
} catch (error) {
reporter.error(error.message)
process.exit(1)
}

const selectedOptions = {
typeScript: argv.typescript ?? true,
packageManager:
argv.packageManager ?? getPackageManager() ?? 'pnpm',
templateSource: argv.template ?? 'basic',
templateSource: resolvedPluginOptions.template ?? 'basic',
pluginType: resolvedPluginOptions.pluginType,
}

if (!useDefauls) {
Expand All @@ -111,7 +142,7 @@ const command = {
selectedOptions.typeScript = language === 'ts'
}

if (argv.template === undefined) {
if (resolvedPluginOptions.template === undefined) {
const template = await select({
message: 'Select a template',
default: 'basic',
Expand All @@ -121,6 +152,10 @@ const command = {
name: 'Template with React Router',
value: 'react-router',
},
{
name: 'Plugin (Capture or Dashboard)',
value: 'plugin',
},
{
name: 'Custom template from Git',
value: 'custom-git',
Expand All @@ -138,6 +173,30 @@ const command = {
selectedOptions.templateSource = template
}
}

if (
selectedOptions.templateSource === 'plugin' &&
argv.pluginType === undefined
) {
selectedOptions.pluginType = await select({
message: 'Which kind of plugin?',
choices: pluginTypes.map(({ name, value }) => ({
name,
value,
})),
})
}
}

// With --yes there is no prompt, so --pluginType must be passed
try {
assertPluginTypeChosen({
template: selectedOptions.templateSource,
pluginType: selectedOptions.pluginType,
})
} catch (error) {
reporter.error(error.message)
process.exit(1)
}

reporter.info(
Expand All @@ -162,7 +221,9 @@ const command = {

reporter.info(`${chalk.cyan('Selected options:')}`)
for (const [x, y] of Object.entries(selectedOptions)) {
reporter.info(` ${x}: ${y}`)
if (y !== undefined) {
reporter.info(` ${x}: ${y}`)
}
}

try {
Expand All @@ -186,6 +247,14 @@ const command = {

if (builtInTemplatePath) {
fs.copySync(builtInTemplatePath, cwd)
if (selectedOptions.templateSource === 'plugin') {
// plugin = shared base + the files for one plugin type
fs.copySync(
getPluginOverlayDirectory(selectedOptions.pluginType),
cwd,
{ overwrite: true }
)
}
} else {
resolvedExternalTemplate = await resolveExternalTemplateSource(
selectedOptions.templateSource
Expand Down Expand Up @@ -330,7 +399,10 @@ const command = {
})

reporter.debug(' Deleting TS files')
const filePathsToRemove = path.join(paths.base, '/src/**/*.ts[x]')
const filePathsToRemove = path.join(
paths.base,
'/src/**/*.{ts,tsx}'
)
const filesToRemove = await fg.glob(filePathsToRemove)

filesToRemove.forEach((file) => {
Expand Down
89 changes: 89 additions & 0 deletions packages/create-app/src/utils/pluginTemplates.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
const path = require('path')

Check warning on line 1 in packages/create-app/src/utils/pluginTemplates.js

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Prefer `node:path` over `path`.

See more on https://sonarcloud.io/project/issues?id=dhis2_cli&issues=AaIyKhF-Gzjp9lsPUZTI&open=AaIyKhF-Gzjp9lsPUZTI&pullRequest=644

const templatesRoot = path.join(__dirname, '../../templates')

const pluginBaseTemplateDirectory = path.join(
templatesRoot,
'template-ts-plugin'
)

const pluginTypes = [
{
value: 'form-field',
name: 'Capture: form field plugin',
pluginType: 'CAPTURE_FORM_FIELD',
},
{
value: 'enrollment',
name: 'Capture: enrollment page plugin',
pluginType: 'CAPTURE_ENROLLMENT',
},
{
value: 'bulk-data-entry',
name: 'Bulk data entry plugin',
pluginType: 'TRACKER_BULK_DATA_ENTRY',
},
{
value: 'dashboard',
name: 'Dashboard plugin',
pluginType: 'DASHBOARD',
},
]

const pluginTypeValues = pluginTypes.map(({ value }) => value)

const isValidPluginType = (value) => pluginTypeValues.includes(value)

const getPluginOverlayDirectory = (value) => {
if (!isValidPluginType(value)) {
throw new Error(
`Unknown plugin type "${value}". Valid plugin types: ${pluginTypeValues.join(
', '
)}`
)
}
return path.join(templatesRoot, 'plugin-types', value)
}

/**
* Works out the template and plugin type from CLI args.
* Passing --pluginType on its own implies --template plugin.
*/
const resolvePluginOptions = ({ template, pluginType }) => {
if (pluginType !== undefined && template === undefined) {
return { template: 'plugin', pluginType }
}
if (template === 'plugin') {
return { template, pluginType }
}
if (pluginType !== undefined) {
throw new Error(
`--pluginType can only be used with --template plugin (got --template ${template})`
)
}
return { template, pluginType: undefined }
}

/**
* Throws if the plugin template was chosen without a plugin type, e.g.
* `--template plugin --yes`, where there is no prompt to ask for one.
*/
const assertPluginTypeChosen = ({ template, pluginType }) => {
if (template === 'plugin' && pluginType === undefined) {
throw new Error(
`--pluginType is required with --template plugin. Choose one of: ${pluginTypeValues.join(
', '
)}`
)
}
}

module.exports = {
pluginBaseTemplateDirectory,
pluginTypes,
pluginTypeValues,
isValidPluginType,
getPluginOverlayDirectory,
resolvePluginOptions,
assertPluginTypeChosen,
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/** @type {import('@dhis2/cli-app-scripts').D2Config} */
const config = {
type: 'app',

entryPoints: {
// Local development harness only (renders Plugin.tsx with mocked
// props). Remove before release if you don't want an app entry.
app: './src/App.tsx',
plugin: './src/Plugin.tsx',
},

// Capture plugin types: CAPTURE_FORM_FIELD, CAPTURE_ENROLLMENT,
// TRACKER_BULK_DATA_ENTRY. The Capture app does not
// read this value (plugins are wired up in the Tracker Plugin
// Configurator); it describes the plugin in /api/apps and the App Hub.
pluginType: 'TRACKER_BULK_DATA_ENTRY',

viteConfigExtensions: './viteConfigExtensions.mts',
}

module.exports = config
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Local development harness - NOT loaded by Capture.
*
* Renders Plugin.tsx with mocked props shaped like the ones Capture passes.
*/
import React, { FC, useState } from 'react'
import classes from './App.module.css'
import Plugin from './Plugin'

const mockTrackedEntityIds = ['a1B2c3D4e5F', 'g6H7i8J9k0L', 'm1N2o3P4q5R']

const App: FC = () => {
const [log, setLog] = useState<string[]>([])

const record = (line: string) => {
console.log(line)
setLog((prev) => [...prev, line])
}

return (
<div className={classes.harness}>
<h2>Bulk data entry plugin harness</h2>
<div className={classes.pluginFrame}>
<Plugin
configKey="my-bulk-config"
trackedEntityIds={mockTrackedEntityIds}
onComplete={async () => record('onComplete()')}

Check warning on line 27 in packages/create-app/templates/plugin-types/bulk-data-entry/src/App.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Review this async function: it has no await expression.

See more on https://sonarcloud.io/project/issues?id=dhis2_cli&issues=AaIyKhF6Gzjp9lsPUZTE&open=AaIyKhF6Gzjp9lsPUZTE&pullRequest=644
onDefer={() => record('onDefer()')}
/>
</div>
<div className={classes.log}>
{log.join('\n') || 'No calls yet'}
</div>
</div>
)
}

export default App
Loading
Loading