Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code-based plugin parameter docs #2877

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ coverage/
dist.zip
packages/jspsych/README.md
.turbo
*.pyc
docs/__generator__/cache
159 changes: 159 additions & 0 deletions docs/__generator__/plugins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
from pathlib import Path

from docs.__generator__.utils import (
convert_blockquote_admonitions,
generate_badge_svg,
get_package_info,
get_plugin_description,
get_value_by_path,
get_values_by_path,
jsdoc_to_inline_markdown,
jsdoc_to_markdown,
plugin_name_to_camel_case,
)

PARAMETER_TYPE_MAPPING = {
"KEYS": "array of strings",
"BOOL": "boolean",
"STRING": "string",
"INT": "numeric",
"FLOAT": "numeric",
"FUNCTION": "function",
"KEY": "string",
"KEYS": "array of strings",
# "SELECT": "",
"HTML_STRING": "HTML string",
"IMAGE": "image file",
"AUDIO": "audio file",
"VIDEO": "video file",
# "OBJECT": "",
# "COMPLEX": "",
# "TIMELINE": "",
}


def generate_plugin_parameters_section(plugin_dir: Path):
description = get_plugin_description(plugin_dir)

output = """
## Parameters

In addition to the [parameters available in all
plugins](../overview/plugins.md#parameters-available-in-all-plugins), this plugin
accepts the following parameters. Parameters with a default value of undefined must be
specified. Other parameters can be left unspecified if the default value is acceptable.

| Parameter | Type | Default Value | Description |
| --------- | ---- | ------------- | ----------- |
"""

for parameter in get_values_by_path(
description,
"$.children[?name = default].children[?name = info].type.declaration.children[?name = parameters].type.declaration.children[?kindString = Property]",
):
parameter_name = parameter["name"]

parameter_type = get_value_by_path(
parameter, "$.type.declaration.children[?name = type].type.name"
)
if parameter_type in PARAMETER_TYPE_MAPPING:
parameter_type = PARAMETER_TYPE_MAPPING[parameter_type]

is_array = get_value_by_path(
parameter, "$.type.declaration.children[?name = array].type.value"
)
if is_array:
parameter_type = f"array of {parameter_type}s"

default_value_description = get_value_by_path(
parameter, "$.type.declaration.children[?name = default]"
)

# If `default_value` has a TSDoc summary, display it as the default value
default_value_summary = get_value_by_path(
default_value_description, "$.comment.summary"
) or get_value_by_path(
default_value_description,
"$.type.declaration.signatures[0].comment.summary",
)
if default_value_summary:
default_value = jsdoc_to_inline_markdown(default_value_summary)
else:
default_value = get_value_by_path(
default_value_description, "$.defaultValue"
)

# Large arrays are not displayed by default, so assembling a custom string
# here
if is_array and default_value == "...":
default_array_values = get_values_by_path(
default_value_description, "$.type.target.elements[*].value"
)

if default_array_values:
separator = '", "'
default_value = f'["{separator.join(default_array_values)}"]'

is_required = default_value == "undefined"
required_marker = "<font color='red'>*</font>" if is_required else ""
if is_required:
default_value = ""

description = jsdoc_to_inline_markdown(
get_values_by_path(parameter, "$.comment.summary[*]")
)

output += f"{parameter_name}{required_marker} | {parameter_type} | {default_value} | {description} \n"

return output


def generate_plugin_summary(plugin_dir: Path):
summary = get_value_by_path(
get_plugin_description(plugin_dir),
"$.children[?name = default].comment.summary",
)
return convert_blockquote_admonitions(jsdoc_to_markdown(summary))


def generate_plugin_version_info(plugin_dir: Path):
info = get_package_info(plugin_dir)
return f"[{generate_badge_svg('Current version',info['version'])}](https://github.com/jspsych/jsPsych/blob/main/{plugin_dir}/CHANGELOG.md)"


def generate_plugin_author_info(plugin_dir: Path):
author = get_value_by_path(
get_plugin_description(plugin_dir),
"$.children[?name = default].comment.blockTags[?tag = @author].content[0].text",
)
return generate_badge_svg("Author", author, "lightgray")


def generate_plugin_installation_section(plugin_dir: Path):
info = get_package_info(plugin_dir)
plugin_dir_name = plugin_dir.name

return f"""
## Install

Using the CDN-hosted JavaScript file:

```js
<script src="https://unpkg.com/{info["name"]}@{info["version"]}"></script>
```

Using the JavaScript file downloaded from a GitHub release dist archive:

```js
<script src="jspsych/{plugin_dir_name}.js"></script>
```

Using NPM:

```
npm install {info["name"]}
```
```js
import {plugin_name_to_camel_case(plugin_dir_name)} from '{info["name"]}';
```
"""
135 changes: 135 additions & 0 deletions docs/__generator__/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import json
import subprocess
from hashlib import md5
from logging import getLogger
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any, List

import requests
from diskcache import Cache
from jsonpath_ng.ext import parse

cache = Cache(Path(__file__).parent / "cache")
logger = getLogger("mkdocs")


def hash_file(path: Path):
with path.open() as file:
return md5(file.read().encode("utf8")).hexdigest()


def get_plugin_description(plugin_dir: Path):
cache_key = (
"get_plugin_description",
plugin_dir,
hash_file(plugin_dir / "src/index.ts"),
)
if cache_key in cache:
return cache[cache_key]

logger.info(f"Collecting parameter infos for {plugin_dir}...")
with NamedTemporaryFile() as json_file:

typedoc_command = (
subprocess.list2cmdline(
[
"node_modules/.bin/typedoc",
"--tsconfig",
plugin_dir / "tsconfig.json",
"--json",
f"{json_file.name}",
"--sort",
"source-order",
plugin_dir / "src/index.ts",
]
),
)

subprocess.run(
typedoc_command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)

description = json.load(json_file)

cache[cache_key] = description
return description


def get_values_by_path(data, json_path: str):
return [match.value for match in parse(json_path).find(data)]


def get_value_by_path(data, json_path: str):
values = get_values_by_path(data, json_path)
return values[0] if len(values) > 0 else None


def jsdoc_to_markdown(fragments: List[Any]):
output = ""

for fragment in fragments:
if fragment["kind"] in ["text", "code"]:
output += fragment["text"]

elif fragment["kind"] == "inline-tag":
if fragment["tag"] == "@link":
output += (
f'[{fragment["text"] or fragment["target"]}]({fragment["target"]})'
)

return output


def jsdoc_to_inline_markdown(fragments: List[Any]):
return jsdoc_to_markdown(fragments).replace("\n\n", "<p>").replace("\n", " ")


def convert_blockquote_admonitions(input: str):
"""
Replace blockquote-based admonitions with MkDocs' admonition style
"""
lines = input.split("\n")
is_blockquote = False
for index, line in enumerate(lines):
if line.startswith("> **"):
lines[index] = "!!! " + line[2:].replace("**", "")
is_blockquote = True

elif is_blockquote:
if line.startswith(">"):
lines[index] = " " + line[2:]
else:
is_blockquote = False

return "\n".join(lines)


def plugin_name_to_camel_case(plugin_name: str):
words = plugin_name.split("-")
return words[1] + "".join([word.capitalize() for word in words[2:]])


@cache.memoize(name="get_package_info", expire=60)
def get_package_info(package_dir: Path):
with (package_dir / "package.json").open() as package_json_file:
package_json = json.load(package_json_file)
return {"name": package_json["name"], "version": package_json["version"]}


@cache.memoize(name="generate_badge_svg")
def generate_badge_svg(label: str, message: str, color="4cae4f"):

return requests.get(
f"https://img.shields.io/static/v1",
params={
"label": label,
"message": message,
"color": color,
"style": "flat-square",
},
).text
29 changes: 29 additions & 0 deletions docs/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from pathlib import Path

from docs.__generator__.plugins import (
generate_plugin_author_info,
generate_plugin_installation_section,
generate_plugin_parameters_section,
generate_plugin_summary,
generate_plugin_version_info,
)


# https://mkdocs-macros-plugin.readthedocs.io/en/latest/macros/
def define_env(env):
@env.macro
def plugin_parameters(plugin: str):
return generate_plugin_parameters_section(Path(f"packages/plugin-{plugin}"))

@env.macro
def plugin_description(plugin: str):
return generate_plugin_summary(Path(f"packages/plugin-{plugin}"))

@env.macro
def plugin_meta(plugin: str):
plugin_dir = Path(f"packages/plugin-{plugin}")
return f"{generate_plugin_version_info(plugin_dir)} {generate_plugin_author_info(plugin_dir)}\n"

@env.macro
def plugin_installation(plugin: str):
return generate_plugin_installation_section(Path(f"packages/plugin-{plugin}"))
52 changes: 4 additions & 48 deletions docs/plugins/audio-button-response.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,8 @@
# audio-button-response

Current version: 1.1.2. [See version history](https://github.com/jspsych/jsPsych/blob/main/packages/plugin-audio-button-response/CHANGELOG.md).

This plugin plays audio files and records responses generated with a button click.

If the browser supports it, audio files are played using the WebAudio API. This allows for reasonably precise timing of the playback. The timing of responses generated is measured against the WebAudio specific clock, improving the measurement of response times. If the browser does not support the WebAudio API, then the audio file is played with HTML5 audio.

Audio files can be automatically preloaded by jsPsych using the [`preload` plugin](preload.md). However, if you are using timeline variables or another dynamic method to specify the audio stimulus, you will need to [manually preload](../overview/media-preloading.md#manual-preloading) the audio.

The trial can end when the participant responds, when the audio file has finished playing, or if the participant has failed to respond within a fixed length of time. You can also prevent a button response from being made before the audio has finished playing.

## Parameters

In addition to the [parameters available in all plugins](../overview/plugins.md#parameters-available-in-all-plugins), this plugin accepts the following parameters. Parameters with a default value of *undefined* must be specified. Other parameters can be left unspecified if the default value is acceptable.

| Parameter | Type | Default Value | Description |
| ------------------------------ | ---------------- | ---------------------------------------- | ---------------------------------------- |
| stimulus | audio file | *undefined* | Path to audio file to be played. |
| choices | array of strings | *undefined* | Labels for the buttons. Each different string in the array will generate a different button. |
| button_html | HTML string | `'<button class="jspsych-btn">%choice%</button>'` | A template of HTML for generating the button elements. You can override this to create customized buttons of various kinds. The string `%choice%` will be changed to the corresponding element of the `choices` array. You may also specify an array of strings, if you need different HTML to render for each button. If you do specify an array, the `choices` array and this array must have the same length. The HTML from position 0 in the `button_html` array will be used to create the button for element 0 in the `choices` array, and so on. |
| prompt | string | null | This string can contain HTML markup. Any content here will be displayed below the stimulus. The intention is that it can be used to provide a reminder about the action the participant is supposed to take (e.g., which key to press). |
| trial_duration | numeric | null | How long to wait for the participant to make a response before ending the trial in milliseconds. If the participant fails to make a response before this timer is reached, the participant's response will be recorded as null for the trial and the trial will end. If the value of this parameter is null, the trial will wait for a response indefinitely. |
| margin_vertical | string | '0px' | Vertical margin of the button(s). |
| margin_horizontal | string | '8px' | Horizontal margin of the button(s). |
| response_ends_trial | boolean | true | If true, then the trial will end whenever the participant makes a response (assuming they make their response before the cutoff specified by the `trial_duration` parameter). If false, then the trial will continue until the value for `trial_duration` is reached. You can set this parameter to `false` to force the participant to listen to the stimulus for a fixed amount of time, even if they respond before the time is complete. |
| trial_ends_after_audio | boolean | false | If true, then the trial will end as soon as the audio file finishes playing. |
| response_allowed_while_playing | boolean | true | If true, then responses are allowed while the audio is playing. If false, then the audio must finish playing before the button choices are enabled and a response is accepted. Once the audio has played all the way through, the buttons are enabled and a response is allowed (including while the audio is being re-played via on-screen playback controls). |
{{ plugin_meta('audio-button-response') }}
{{ plugin_description('audio-button-response') }}
{{ plugin_parameters('audio-button-response') }}

## Data Generated

Expand All @@ -42,28 +19,7 @@ In `data-only` simulation mode, the `response_allowed_while_playing` parameter d
This is because the audio file is not loaded in `data-only` mode and therefore the length is unknown.
This may change in a future version as we improve the simulation modes.

## Install

Using the CDN-hosted JavaScript file:

```js
<script src="https://unpkg.com/@jspsych/[email protected]"></script>
```

Using the JavaScript file downloaded from a GitHub release dist archive:

```js
<script src="jspsych/plugin-audio-button-response.js"></script>
```

Using NPM:

```
npm install @jspsych/plugin-audio-button-response
```
```js
import audioButtonResponse from '@jspsych/plugin-audio-button-response';
```
{{ plugin_installation('audio-button-response') }}

## Examples

Expand Down
Loading