Skip to content

Commit

Permalink
Implement plugin_meta, plugin_description and `plugin_installatio…
Browse files Browse the repository at this point in the history
…n` macros
  • Loading branch information
bjoluc committed Nov 28, 2022
1 parent cc7d497 commit 8be09f9
Show file tree
Hide file tree
Showing 12 changed files with 446 additions and 204 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,4 @@ dist.zip
packages/jspsych/README.md
.turbo
*.pyc
cache.db
docs/__generator__/cache
108 changes: 101 additions & 7 deletions docs/__generator__/plugins.py
Original file line number Diff line number Diff line change
@@ -1,23 +1,38 @@
from pathlib import Path

from docs.__generator__.utils import (
cache,
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 = {
"HTML_STRING": "HTML string",
"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": "",
}


@cache.memoize(expire=60 * 60 * 24 * 30) # 1 month in seconds
def generate_plugin_parameters_section(plugin_dir: Path, source_hash: str):
def generate_plugin_parameters_section(plugin_dir: Path):
description = get_plugin_description(plugin_dir)

output = """
Expand Down Expand Up @@ -47,19 +62,98 @@ def generate_plugin_parameters_section(plugin_dir: Path, source_hash: str):
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 = get_value_by_path(
parameter, "$.type.declaration.children[?name = default].defaultValue"
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_markdown(
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"]}';
```
"""
82 changes: 72 additions & 10 deletions docs/__generator__/utils.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import json
from logging import getLogger
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 = Cache(Path(__file__).parent / "cache")
logger = getLogger("mkdocs")


Expand All @@ -19,6 +20,14 @@ def hash_file(path: Path):


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:

Expand Down Expand Up @@ -47,7 +56,8 @@ def get_plugin_description(plugin_dir: Path):

description = json.load(json_file)

return description
cache[cache_key] = description
return description


def get_values_by_path(data, json_path: str):
Expand All @@ -59,15 +69,67 @@ def get_value_by_path(data, json_path: str):
return values[0] if len(values) > 0 else None


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

for part in parsed_parts:
if part["kind"] in ["text", "code"]:
output += part["text"].replace("\n\n", "<p>").replace("\n", " ")
for fragment in fragments:
if fragment["kind"] in ["text", "code"]:
output += fragment["text"]

elif part["kind"] == "inline-tag":
if part["tag"] == "@link":
output += f'[{part["text"] or part["target"]}]({part["target"]})'
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
24 changes: 19 additions & 5 deletions docs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
from pathlib import Path

from docs.__generator__.plugins import generate_plugin_parameters_section
from docs.__generator__.utils import hash_file
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"

return generate_plugin_parameters_section(
plugin_dir, hash_file(plugin_dir / "src/index.ts")
)
@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/plugin-audio-button-response@1.1.2"></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

0 comments on commit 8be09f9

Please sign in to comment.