Reference
You are browsing documentation for an upcoming version of PageDriver. Documentation and features of this release are subject to change.
Can't find what you're looking for?
If you find yourself going to 3rd parties for answers (such as StackOverflow), please search our documentation issue list first, and submit your question if one doesn't already exist.
β Frequently used functionality is highlighted.
namespace BIND
Binds allow the creation of extendable interface-like structures.
Any object may have bindings, but only the object itself should execute them. Currently we don't prevent 'external' bind execution, however prevention may be enforced in the future.
BindRegistry > BindInterface > Binding
typedef BindRegistry Object.<string, BindInterface>
A bind registry is a collection of bind interfaces.
Object.<string, BindInterface>
bind interfaces.
typedef BindFilter function(triggers, args, iterator)β boolean
Custom function used by bindExec to limit execution of bound handlers.
function(triggers, args, iterator)β boolean
bindExec to limit execution of bound handlers.Returns: boolean β True when at least one exact matching trigger is found.
| Parameter | Type | Description |
|---|---|---|
| triggers | string | Used by the filter function receiving the current bind ID iteration. |
| args | object | Arguments passed to bound function. |
| iterator | number | Current bind ID (interface list array index). Utilize in the following way: |
typedef BindInterface object
A single interface within a BindRegistry.
object
BindRegistry.Extends: BIND.BindInterfaceInit
BindInterfaces go through an optional 'PLACEHOLDER' state when code attempts to getBindInterface or bind an uninitialized interface.
Properties
- PLACEHOLDER
boolean(INTERNAL) True when non-existant interface is loaded or bound to.
- name
stringSelf-reflection, primarily for debugging.
- [mustBeNamed =
true]booleanDEFAULT TRUE. When true, causes a
TypeErrorto be thrown when attempting to bind anonymous functions. - [freezeHandler =
true]booleanHARDCODED TRUE. Prevents modification of the handler function. Setting this to
falsewould allow in-situ replacement of bound function handles. If you have a practical use case for this please contact the CORE development team. - [add]
functionaddAdditional processing when adding a binding. Can abort the process... by throwing an error :P - [disable]
functiondisableAdditional processing when disabling bindings. Bindings are never deleted, only disabled - usually by settingrunsRemainingto-1. - [filter]
BindFilter - [execOnAdd]
object(EXPERIMENT) Simulated execution
argsused during initial binding whenexecOnAddis true. SeeBIND/bindoptions.to add/remove binds. Does it make more sense to allow unique simulated args on a per-bindExec basis instead? Feedback welcome. - list
Array.<Binding> - addedAt
DOMHighResTimeStamp - [scopes]
Object.<string, Array.<number>>(CONCEPT) for lookups? Could use code similar to EVENT add/disable bindings. Currently there is experimental scoping at the per-bind level.
typedef add function(triggers, fn, [position])
function(triggers, fn, [position])
Extends: BIND.bind
| Parameter | Type | Description |
|---|---|---|
| triggers | Array.<string> | string | Array of strings, or a string which is split by spaces and converted into an array. Used by bind execution filter. |
| fn | function | Executed when triggers pass the |
| [position] | number | (EXPERIMENT) Current execution index |
typedef disable function(bindTarget, id)
function(bindTarget, id)
Extends: BIND.disableBindByID
| Parameter | Type | Description |
|---|---|---|
| bindTarget | BindTarget | |
| id | number | bind ID # |
typedef BindInterfaceInit object
object
Properties
- [mustBeNamed =
true]booleanDEFAULT TRUE. When true, causes a
TypeErrorto be thrown when attempting to bind anonymous functions. - [freezeHandler =
true]booleanHARDCODED TRUE. Prevents modification of the handler function. Setting this to
falsewould allow in-situ replacement of bound function handles. If you have a practical use case for this please contact the CORE development team. - [filter]
BindFilter - [add]
functionaddAdditional processing when adding a binding. Can abort the process... by throwing an error :P - [disable]
functiondisableAdditional processing when disabling bindings. Bindings are never deleted, only disabled - usually by settingrunsRemainingto-1.
typedef Binding object
Single binding within a BindInterface for potential execution by bindExec.
object
BindInterface for potential execution by bindExec.Properties
- triggers
Array.<string>Array of strings used by the bind execution filter
BindFilter. - [scope]
Array.<string>|string(EXPERIMENT) secondary filtering layer, primarily intended for DOM based filtering, but who knows...
- handler
functionexecuted when
triggerspasses thebindExecfilter. It is scoped to this object (thisreturns the current Binding). - id
numberarray ID, pretty much only useful for self removal.
- runsRemaining
numberDefaults to
Infinity. - stats
objectIdeally moved to an accessible dedicated stats module allowing custom reporting, as adding binds to the binds module seems like a terrible idea.
- stats.added
DOMHighResTimeStampCurrently
performance.now. Likely to change. See #165Date.now()in STATS. - stats.runs
Array.<DOMHighResTimeStamp>Times run (get total via
runs.length) - [stats.disabled]
DOMHighResTimeStampCreated when bind is deactivated successfully
typedef BindTarget object | function
Any non-primitive with a BindInterface property.
object | function
BindInterface property.Properties: boundInterface BindInterface
constant defaultBindRegistry BindRegistry β
Project's default binding registry.
BindRegistry β
Categories: BIND, devTools
basicDOMFilter β¨BindFilterβ boolean
Default bind filter used by bindExec unless a custom filter function is provided.
BindFilterβ boolean
bindExec unless a custom filter function is provided.Implements: BindFilter
bind(target, triggers, handler, [options])β number
Register a function that executes when the triggers parameter passes the target interface's bindExec filter.
number
triggers parameter passes the target interface's bindExec filter.Returns: number β Bind's position in the target interface's queue (execution order when executing)
| Parameter | Type | Description |
|---|---|---|
| target | string | Destination interface name. |
| triggers | Array.<string> | string | Array of strings, or a string which is split by spaces and converted into an array. Used by bind execution filter. |
| handler | function | Executed when triggers pass the |
| [options] | object | |
[options.runsRemaining = Infinity] | number | (EXPERIMENT) Deactivates the bind function after a set number of successful executions. Remaining runs decrease when the bound function returns |
| [options.execOnAdd] | boolean | (EXPERIMENT) Executes the function when added, against predefined trigger data. |
| [options.scope] | Array.<string> | string | (EXPERIMENT) secondary execution filter, was originally intended for DOM based filtering. |
bindAll(scope, target, trigger, binds, [options])β Array.<number>
Most useful in modules with many similar bindings.
Array.<number>
Returns: Array.<number> β Bind IDs
| Parameter | Type | Description |
|---|---|---|
| scope | string | |
| target | BindTarget | |
| trigger | string | Array.<string> | |
| binds | Object | Array.<function(), object> | a function, or an array containing the function and specific bind options |
| [options] | object | Passed through to |
bindExec(target, triggers, args, [meta])β boolean
Execute bound functions which passed filtration.
boolean
Returns: boolean β True if any bind was executed. This may change in the future to 'successful' calls only, feedback welcome!
| Parameter | Type | Description |
|---|---|---|
| target | string | destination bind interface. |
| triggers | string | Array.<string> | Used by the filter function receiving the current bind ID iteration. |
| args | object | Arguments passed to bound functions |
| [meta] | object | (EXPERIMENT) Metadata passed to bound function, currently used by pd.OBSERVE |
getBindRegistryβ BindRegistry
Directly access a binding registry for live debugging, this fails outside of the DEBUG context.
BindRegistry
Categories: BIND, devTools
initBindInterface(target, [options], [registry])β BindInterface
Initialize a BindInterface.
BindInterface
BindInterface.Prior to instantiation bindings may be registered to 'placeholder' interfaces; When a placeholder is initialized by this function, all previously added bindings are re-processed to ensure validity.
Best Practices
- We recommend only a single interface is initialized per module to reduce complexity.
- When naming a new interface, you must be very specific to avoid potential conflicts with future potential PageDriver CORE generic interfaces.
- DON'T use the initalizer for accessing other interfaces, use
getBindInterfaceinstead. - Unless complete external access is warranted, exporting interfaces is discouraged.
| Parameter | Type | Description |
|---|---|---|
| target | string | Bind interface name |
| [options] | BindInterfaceInit | Merge/replace default bind interface properties. |
[registry = defaultBindRegistry] | BindRegistry | (EXPERIMENT) Don't change this. |
getBindInterface(target, [registry])β BindInterface
Load a bind interface, when it doesn't exist a special 'placeholder' is created with default values.
BindInterface
| Parameter | Type | Description |
|---|---|---|
| target | string | Bind interface name |
[registry = defaultBindRegistry] | BindRegistry | (EXPERIMENT) Don't change this. |
bindStats(interfaceName, [consoleTable])β Array
Array
Returns: Array β Triggers, function name, total executions, time added, time disabled.
| Parameter | Type | Description |
|---|---|---|
| interfaceName | string | |
| [consoleTable] | boolean | additionally output via |
Categories: devTools
disableBindByID(bindTarget, id)β boolean
Deactivate a specific bind.
boolean
Returns: boolean β Only returns true when a bind is actually disabled, all other situations such as no bindings, or already being disabled returns false.
Optional target specific disable logic can abort this process. Note disabling a binding doesn't delete it, it sets runsRemaining to -1 and records the timestamp to stats.disabled.
| Parameter | Type |
|---|---|
| bindTarget | BindTarget |
| id | number |
namespace CONTEXT
Contexts are flat (non-hierarchical) negatable CSS classes used to toggle element visibility relevant to different personas, states, or permissions.
For example, elements meant for a regular user, moderator, or manager. See ContextName for naming rules.
typedef ContextName string
string
Context class names:
- CANNOT begin with a hyphen (
-). This character is used for negated contexts. - MUST begin with an uppercase character (ex. 'A' not 'a'. 'Π' not 'Π»'. 'Δ' not 'Δ') for differentiation from basic CSS classes. If your chosen programming locale doesn't have capitalization we recommend standardizing a basic latin script prefix (ex.
CCγγ°γ€γ³γγ,CCλ‘κ·ΈμΈ) across your project. - CANNOT be a
reserved name.
Valid examples:
"Vendor"Basic Latin uppercase"ΠΠΈΠ΄Π΅Ρ"Cyrillic uppercase"ΔαΊ·c_Quyα»n"Vietnamese uppercase with underscore"CCγγ°γ€γ³γγ"prefixed with uppercase latin script
Invalid examples:
"-Vendor"starts with hyphen (use for negation)"vendor"starts lowercased"123User"starts with number, note as of 2025/1/1 this is not enforced programmatically given classes are not normally permitted to begin with numbers.
See isValidContextName for the runtime validation.
typedef ContextState object
State of a single Context within the global context container.
object
Properties
- state
boolean - added
EpochTimeStamp - [modified]
EpochTimeStamp
typedef ContextClass Object.<ContextName, ContextState>
Object.<ContextName, ContextState>
constant globalContextState Object.<ContextName, ContextState>
Global context state object.
Object.<ContextName, ContextState>
constant globalContextStateReserved Array.<ContextName>
Array.<ContextName>
Current reserved context names:
Javascript- Always actived (activated duringINIT).-Javascriptis an alternative to<noscript>tags.Debug- Active when DEBUG module debugger is loaded.Kbd- Accessibility (a11y) helper, active when using keyboard-like controls.
contextInit(contexts) β
Generates Context Flag CSS styles.
| Parameter | Type |
|---|---|
| contexts | Object.<ContextName, boolean> |
isValidContextName(contextName)β boolean β
Ensure potential context names are in proper form (non-negated and begin with a capital character).
boolean β
Throws: TypeError β when contextName is not a string.
| Parameter | Type |
|---|---|
| contextName | string |
contextOff(contexts)β Object.<ContextName, ContextState>
Syntactic sugar for set( ... , false).
Object.<ContextName, ContextState>
set( ... , false).Returns: Object.<ContextName, ContextState> β Returns an empty object when no provided contexts are valid.
| Parameter | Type |
|---|---|
| contexts | Array.<ContextName> | ContextName |
contextOn(contexts)β Object.<ContextName, ContextState>
Syntactic sugar for set( ... , true).
Object.<ContextName, ContextState>
set( ... , true).Returns: Object.<ContextName, ContextState> β Returns an empty object when no provided contexts are valid.
| Parameter | Type |
|---|---|
| contexts | Array.<ContextName> | ContextName |
contextSet(contexts, [state])β Object.<ContextName, ContextState>
Context Flag base function.
Object.<ContextName, ContextState>
Returns: Object.<ContextName, ContextState> β Returns an empty object when no provided contexts are valid.
Throws: Error β when no contexts are provided.
Used by on/off/toggle helpers.
| Parameter | Type | Description |
|---|---|---|
| contexts | Array.<ContextName> | ContextName | |
| [state] | undefined | boolean |
|
contextToggle(contexts)β boolean | Object.<ContextName, ContextState>
Syntactic sugar for set( ... , undefined ), EXCEPT when a SINGLE (1) Context is provided it only returns the boolean state result, allowing for cleaner inlining.
boolean | Object.<ContextName, ContextState>
set( ... , undefined ), EXCEPT when a SINGLE (1) Context is provided it only returns the boolean state result, allowing for cleaner inlining.Returns: boolean | Object.<ContextName, ContextState> β Boolean when only a single Context is provided.
Toggling an undefined Context creates it (in true state).
| Parameter | Type | Description |
|---|---|---|
| contexts | Array.<ContextName> | ContextName | One or more context flags |
Example
contextToggle('Foo'); // Returns a boolean
contextToggle(['Foo','Bar']); // Returns { ContextState, ... }
module DEBUG
In-browser PageDriver debug tools.
The Debugger object and functionality is made available under the pd.DEBUG global property. It is activated under any of the following conditions:
- 'debug' cookie exists during standard PageDriver initiation.
- The 'debug.mjs' module is imported.
Due to active development some functions are likely undocumented on the reference page.
Properties
- verboseActive
numberTotal active verbose DEBUG flags.
- initDOMSize
numberNumber of initial
document.bodyDOM elements. - verbose
Proxy.<string, boolean>Verbosity flag proxy, used for customization of debug messages - these appear in the in-browser debugger 'Verbose' toggle list. Ex.
if (pd.DEBUG?.verbose.myAwesomeFunction) console.log('Yippie!'). Be mindful as there are no 'reserved' verbose flags or groups (yet), so ensure:- your output is as specific as possible to a particular flag, or set of flags.
- the verbose flag property name is specific enough.
- once
Proxy.<string, boolean>Proxy object that returns
trueonly on first access, useful for one-off console messages.
Categories: devTools
remoteDebuggingβ boolean
True when the client has remote debug permissions.
boolean
module OBSERVER
Project-wide bindable DOM mutation observer.
This module only supports a single active observer for no real reason, although performance and coder sanity are a good excuse as any.
Properties: execOnAdd
event childList
Properties: mutation MutationRecord
event attributes
DOESN'T trigger on no-difference attribute mutations for potential performance reasons.
Properties
- args
MutationRecord - meta
object{attributeValue, addAttribute, delAttribute, addAttributeValue, delAttributeValue}
event rawβ mutationsList
Provides raw mutationLists instead of individual records.
mutationsList
filter β¨BindFilter
BindFilter
Implements: BindFilter
Returns true when unscoped, otherwise if there is a mutation target:
- if a
childListwith added nodes, ensure scope is within target - if an
attribute, ensure scope matches the attribute name - all other circumstances return true (ex.
characterData, which as of 2024/12/15 isn't implemented)
namespace DOM
Document Object Model functionality.
DOM best practices
- Instead of mutating HTML directly try using:
- Predefined template elements.
- Context classes (feature flagged areas), or toggleable followups.
- Existing provided 'DOM' and 'UI' functionality.
- Name and group CSS selectors by purpose, not properties. Ex.
.sidenote.important, not.red.col-3.small.
constant DOMState WeakMap.<Element.childNodes>
When mutate mutates nodes, the node's original content is stored here.
WeakMap.<Element.childNodes>
mutate mutates nodes, the node's original content is stored here.I leave it to philosophers to decide if this means we use a VDOM π
constant scratchPadSpace HTMLTextAreaElement β
Scratch space for escape/unescape functions.
HTMLTextAreaElement β
module tableOfContents(parentSelector, [generateAnchors], [maxDepth])β boolean
DOM Renderer - Table of contents.
boolean
Generates generates a table of contents from HTML heading tags, placed in the first located element with the .tableOfContents class.
| Parameter | Type | Description |
|---|---|---|
| parentSelector | string | Single selector, usually a page ID. |
[generateAnchors = true] | boolean | When no anchor is located, one is derived via the closest page ID and slugifying the heading text. |
[maxDepth = 6] | number | Maximum heading depth for generated table, maximum of 6. |
Categories: DOM, renderer
classAdd(el, value)β boolean
Add a CSS class to an element (reduced DOM mutations).
boolean
| Parameter | Type | Description |
|---|---|---|
| el | HTMLElement | |
| value | string | Class name |
classRemove(el, value)β boolean
Remove a CSS class from an element (reduced DOM mutations).
boolean
| Parameter | Type | Description |
|---|---|---|
| el | HTMLElement | |
| value | string | Class name |
DOMcompareNodes(element, element2)β boolean
Compare two DOM nodes for effective equality.
boolean
Returns: boolean β True if element matches original state.
Used by DOM restorer to reduce mutations when restoring elements to their original state from saved fragments.
| Parameter | Type | Description |
|---|---|---|
| element | Element | DocumentFragment | First element or fragment. |
| element2 | Element | DocumentFragment | Second element or fragment. |
DOMSaveState(node, [overwriteExisting], [weakMap])β boolean
Save a DOM Node to a document fragment within a WeakMap.
boolean
Returns: boolean β True when saved.
| Parameter | Type | Description |
|---|---|---|
| node | Node | |
| [overwriteExisting] | boolean | Replace existing saved fragment, disabled by default. |
[weakMap = DOMState] | WeakMap.<Element.childNodes> |
DOMRestoreState(node, [force], [weakMap])β boolean
Restore a DOM node from previously saved state when the node don't match (reduces DOM mutation).
boolean
Returns: boolean β True when restored.
Replaces the target's children with a deep clone of the saved node.
| Parameter | Type | Description |
|---|---|---|
| node | Node | |
| [force] | boolean | When true disables node comparison, forcing replacement and a DOM mutation to occur. Please contact the PageDriver development team with your use case if you find this is necessary (node comparitor may have failed). |
[weakMap = DOMState] | WeakMap.<Element.childNodes> |
removeChildren(target)
A performant alternative to innerHTML=''.
innerHTML=''.| Parameter | Type |
|---|---|
| target | Node |
appendChildren(target, origin, [clone])
Append all origin node children to target node, cloned by default.
| Parameter | Type | Description |
|---|---|---|
| target | Node | |
| origin | Node | |
[clone = true] | boolean | Uses |
escape(text)β string
Escape potential HTML using the browser's built-in innerHTML functionality.
string
innerHTML functionality.If this fails to escape content it means the browser is vulnerable, which is both crazy AND not our problem!
| Parameter | Type |
|---|---|
| text | string |
Example
escape('<script type="module" src="evil.mjs"></script>');
// returns `<script type="module" src="evil.mjs"></script>`
escape('normal & usual');
// returns `normal & usual`
unescape(text)β string
Unescape escaped text using the browser's built-in textContent functionality.
string
textContent functionality.| Parameter | Type |
|---|---|
| text | string |
meta(name, [content])β HTMLMetaElement
Returns existing or creates new <meta> tag in <head>, optionally modifying content attribute.
HTMLMetaElement
<meta> tag in <head>, optionally modifying content attribute.| Parameter | Type |
|---|---|
| name | string |
| [content] | string |
link(rel, [href], [media])β HTMLLinkElement
Mutates or creates (if no match) the first found <link> element within <head> by rel attribute, UNLESS it's a stylesheet - which also matches href attribute.
HTMLLinkElement
<link> element within <head> by rel attribute, UNLESS it's a stylesheet - which also matches href attribute.| Parameter | Type | Description |
|---|---|---|
| rel | string | Relation type https://html.spec.whatwg.org/multipage/links.html#linkTypes |
| [href] | string | |
| [media] | string |
loadScript(src, [options])β Promise
Append a script to the DOM and return loading status to an optional callback.
Promise
Asynchronous and removes own script element after loading by default. This was written before the days of wide browser module support and import / import(). Deprecation or refactor is being considered if the benefits it provides are insufficient.
| Parameter | Type | Description |
|---|---|---|
| src | string | relative or exact URL. |
| [options] | object | |
| [options.callback] | function | Passed |
[options.async = true] | boolean | Asynchronous loading. |
| [options.defer] | boolean | Deferred - executed after the DOM has been parsed, but before firing DOMContentLoaded. |
[options.remove = true] | boolean | Remove script element after loading attempt π§Ή |
| [options.crossorigin] | 'anonymous' | 'use-credentials' | When unspecified |
| [options.integrity] | string | |
[options.module = true] | boolean | Sets |
| [options.nomodule] | boolean | Sets |
markdown(el, [content], [src], [options])β boolean
DOM Renderer - render Markdown to HTML using 'Marked'.
boolean
| Parameter | Type | Description |
|---|---|---|
| el | string | HTMLElement | uses querySelector if not an element. |
| [content] | string | Markdown content |
| [src] | string | Attempts an XHR request for content, overrides |
| [options] | object | |
[options.headerIds = true] | boolean | |
[options.headerPrefix = 'md-'] | string |
Categories: DOM, renderer
renderMarkdown(mr)β boolean β
Internal rendering function.
boolean β
| Parameter | Type |
|---|---|
| mr | HTMLElement | Event |
mutate(root, obj, [options])β stdReturn
stdReturn
Non-object keys are matched to DOM elements via the following rules:
- Elements with 'name' attribute:
- Inexact key match via
[name$="key"]. - (When nested) Exact key match
[name="parentKey[key]"]within nested arrays/objects.
- Inexact key match via
- Elements with any class names starting with
pd_. - (EXPERIMENT) Class names directly matching the nested child object key's name (no 'pd_' required).
Default string, number, boolean type value mutations:
<input>and<select>form fields (radio, checkbox, select).<time>addrelativeattribute to generate a relative locale time.<textarea>updates vertical sizing (may be moved out of CORE).- All others element's content is replaced as PLAIN TEXT. When replacing a non-empty element, its INITIAL content (content not added by the populator) is retained. This content is restored on future calls with an empty string value, allowing for 'default content' in non-input elements. This MAY become a non-default boolean option in a future release - given feedback.
| Parameter | Type | Description |
|---|---|---|
| root | string | HTMLElement | Document | input name prefix eg. prefix_Item, or specific DOM element. For best performance specify an element to allow direct querying when populating a single element and its children, string is useful when targeting multiple root elements. |
| obj | Object.<string, any> | Any object containing state. As of 2022/07/20 we don't allow naked (unnested) arrays, because keys are necessary for DOM query matching. Place the array inside an object, or (not recommended) hijack private |
| [options] | object | |
[options.maxDepth = 10] | number | Maximum allowable nested object recursion depth. If reached mutate() short circuits and returns, preventing additional processing. |
| [options.setDefaultInputs] | Boolean | Permanently replace default input defaults (useful for form resets), this MAY become a special built-in similar to |
[options.template = 'replace'] | 'append' | 'replace' | 'Replace' removes template generated elements when no keys are provided, 'append' retains them. Use 'append' when you want to add duplicate elements. |
| [options.cascade] | Boolean | (EXPERIMENT) (DANGER) Allow simulated user interactions to cascade as if they were real. Test thoroughly to prevent infinite loops! |
| [options.event] | Event | (EXPERIMENT) Likely to be removed. Allows mutate() to skip processing current event target element due to a user event. |
| [options.nested] | Array.<string> | (PRIVATE) Used internally during nested object recursion, usually grouped form inputs. |
| [options.arrayIndex] | Array.<number> | (PRIVATE) Used internally during array recursions. |
Categories: DOM hydrator, renderer, mutator
typedef MutateResult Object
stdReturn result object
Object
Properties
- touched
Array.<Element>Elements virtually clicked.
- mutated
Array.<Element>Elements directly mutated.
- added
Array.<Element>Elements added (usually via template tags)
- removed
numberElements removed during mutation.
- located
numberElements located during queries.
constant result MutateResult β
MutateResult β
stringToSelector(str, [extras])β string
Transforms string to generic CSS selector text, used by mutator() to turn object keys into a generic CSS selector.
string
Returns: string β CSS selector string, ordered by CSS specificity.
| Parameter | Type | Description |
|---|---|---|
| str | string | |
[extras = ''] | string | Appended after each generated selector without any modification. |
Example
stringToSelector('fizz') β '#fizz,.pd_fizz,.fizz,[name$="fizz"],[data-fizz],[data-pd_template-key="fizz"],fizz'
stringToSelector('fizz','.buzz') β '#fizz.buzz,.pd_fizz.buzz,.fizz.buzz,[name$="fizz"].buzz,[data-fizz].buzz,[data-pd_template-key="fizz"].buzz,fizz.buzz'
elementTitle(el)β string
Returns a human readable title from the custom data-name attribute OR derived from the id attribute by replacing - and _ with spaces, trimming whitespace, and capitalizing the first character.
string
data-name attribute OR derived from the id attribute by replacing - and _ with spaces, trimming whitespace, and capitalizing the first character.Returns: string β Empty string when no useable attribute is found.
| Parameter | Type |
|---|---|
| el | HTMLElement |
Example
<article id='reference'>...</article> // 'Reference'
<div id='user_profile-editor'>...</div> // 'User profile editor'
<div id="foo" data-name="returns as is!">...</div> // 'returns as is!'
queryFilter(selector, [root], [nestSelectors], [one])β Array.<HTMLElement>
Returns elements located within root(s) and recursion chain.
Array.<HTMLElement>
Returns: Array.<HTMLElement> β Couldn't this be any Element?
| Parameter | Type | Description |
|---|---|---|
| selector | string | |
[root = document.body] | Element | string | Selector string allows for multiple roots! |
[nestSelectors = []] | Array.<string> | |
| [one] | boolean | Uses |
querySelectParent β
Moved from query.mjs as reference for refactor since it is only referenced in reset
Deprecated
reset(parentSelector, [options]) β
Reset DOM/input state of a node's children.
| Parameter | Type | Description |
|---|---|---|
| parentSelector | object | string | |
| [options] | object | form, readonly, inputs, defaults, hidden, selectNone. If none are used, all options are true. |
| options.form | boolean | reset all inputs in a form |
| options.toDefault | boolean | input fields set to default value |
| options.toInit | boolean | restores non-form elements to initial state. See #166 |
| options.lists | boolean | sponsors / interests? Removes from DOM entirely. |
| options.readonly | boolean | remove |
| options.selection | boolean | revert checked/selected items to blank state |
| options.defaults | boolean | revert checked/selected items back to original state |
| options.hidden | boolean | hidden element values EXCEPT 'readonly' |
| options.selectNone | boolean | simulates click of inputs with "none" value (usually radio inputs) |
| options.inputBackground | boolean | text input backgrounds |
setStyle(styleTagID, options)β HTMLStyleElement
CSS Style loader.
HTMLStyleElement
Creates a new element if no matching style element exists.
| Parameter | Type | Description |
|---|---|---|
| styleTagID | string | Element.id |
| options | object | |
| options.innerText | string | HTMLStyleElement['innerText'] |
Categories: DOM, CSS, loader, mutator
temporary(target, attribute, [value], [options])β DOM.temporary.domTemporaryState
Temporarily mutate HTML element attributes.
DOM.temporary.domTemporaryState
Useful UX Helper that can be used to temporarily add animation classes, disabling buttons, etc.
| Parameter | Type | Description |
|---|---|---|
| target | HTMLElement | |
| attribute | string |
|
[value = ''] | string | optional attribute value. |
| [options] | object | |
| [options.duration] | number | in seconds, derived from computed animation duration (if any) if not supplied. |
| [options.delay] | number | in seconds |
Categories: DOM, mutation, temporal
typedef domTemporaryState object
object
Properties
- timerID
numberTimer ID provided by timeout API
- attribute
string - [value]
string - delay
number - duration
number - status
number0 pending, 1 complete, -1 aborted
constant weakMapDOMTemporary WeakMap.<HTMLElement, DOM.temporary.domTemporaryState> β
Internal state collection.
WeakMap.<HTMLElement, DOM.temporary.domTemporaryState> β
module EVENT
PageDriver browser Event delegator.
This interface is automatically initiated by pd.mjs unless PageDriver modules are being used piecemeal.
Functions bound to the EVENT interface MUST be named to pass the EVENT interface's custom filter rules listed below:
When an event is triggered...
- Sets
lastEventTrustedhelper boolean. - Sets
isKbdhelper boolean. - Monkey patches standard Event object into
module:EVENT~PDEventfor additional properties. - Executes binds passing the custom EVENT interface filter:
- The Event source is trusted OR allowed to cascade.
- AND if bind is scoped, it is the Event target OR within the target (closest).
- AND Event type matches one of the bind's triggers.
- AND ANY of the following:
- Function name begins with
_, which is considered an untargeted 'global' event. - OR function name exactly matches element's ID.
- OR function name matches an HTML tag name within the parent Element chain (nodeNames are ALL CAPS). This check is skipped when the event directly targets an element without a parent node, such as the document root, since they don't have the 'closest' function. Ex.
AorBUTTON. - OR function name matches the
nameattribute in the parent Element chain. - (EXPERIMENT) OR if target is an anchor link AND href attribute beginnings with
#bind-.
- Function name begins with
- Adds
PDEventtopriorEvents(10 max as of 2025/01/20)
Example
bind('EVENT','click', function test(){ console.log('test successful'); });
typedef PDEvent Event
Monkey patched Event.
Event
Properties
- shadowTarget
ElementPopulated with true target when an Event targets an element within an open shadowRoot (via
composedPath()[0]). - pd_cascade
booleanForces EVENT filter to treat a simulated event as real, which may trigger others.
constant EVENT
Default module export
Properties
- isKbd
booleanIs this a keyboard-like event?
trueforKeyboardEventfalseforMouseEventandTouchEventnullfor all other events EXCEPTFocusEvent, where it retains its previous state.
- priorEvents
Array.<module:EVENT~PDEvent>Previously captured events (currently hardcoded as 10).
- lastEventTrusted
booleanBrowser native
event.isTrustedis untrustworthy, use this instead!For whatever reason
event.isTrustedbecomes true when:- a new
MouseEventis dispatched without aneventInitDictparameter. It becomes trusted after dispatch! This may be true for other artificially created events as well. - Follow-up events (such as
input/change) on untrusted form inputclickevents become trusted.
Please see this CodePen for demonstration. Reach out to core team if this is a known "wontfix", or are working on an eventual solution allowing us to remove it.
- a new
- activeListeners
Array.<string>Array of active DOM event types with listeners added via bindAdded to
document, which callpd.EVENT.handler. - notices
State container for one-off developer warnings and notices.
constant boundInterface BindInterface β
BindInterface β
eventHandler(event)
DOM/client Event handler.
See module for logic description.
| Parameter | Type |
|---|---|
| event | module:EVENT~PDEvent |
add(eventName) β¨add β
Adds document element event listeners (unique).
add β
document element event listeners (unique).Implements: BIND.BindInterface.add
| Parameter | Type | Description |
|---|---|---|
| eventName | Array.<string> | Actually <Event['type']> or Array |
disable(eventName) β¨disable β
Removes document element event listeners when no EVENT binds utilizing them remain.
disable β
document element event listeners when no EVENT binds utilizing them remain.Implements: BIND.BindInterface.disable
| Parameter | Type | Description |
|---|---|---|
| eventName | Array.<string> | Event['type'] |
filter(_trigger, event, iterator) β¨BindFilterβ boolean β
Event Filter
BindFilterβ boolean β
Implements: BindFilter
See module description for logic explanation.
| Parameter | Type |
|---|---|
| _trigger | * |
| event | module:EVENT~PDEvent |
| iterator | Number |
namespace HELPER
PageDriver CORE team helper functions.
module RegExps
Central repository of all non-trivial regular expressions.
constant RegExpOnlyFirstSentence RegExp
Extracts the first sentence, but only if it does not look like a list heading or item.
RegExp
Match the first sentence of text from a paragraph including the optional period. May potentially contain generic tags < ... > and code within either curly braces or backticks. First sentence may also end on a new line instead of a period. Avoids lines starting with a spaced hypen (list item), or ending with a colon : as it usually precedes a list.
Tutorial: https://regex101.com/r/LiLwk1/4
constant RegExpJSDOCLink RegExp
Extract links and optional display text from JSDOC {@link} tags outside backticks.
RegExp
{@link} tags outside backticks.Ideally RegExp is refactored to prevent returning backticked content entirely, until then you must check if either other groups are returned. Match groups:
- URL or path.
- (Optional) display text, trims optional
|pipe separator.
Tutorial: https://regex101.com/r/Bvtw5o/3
constant RegExpSafeStringLocator RegExp
Locates #{...} text, returning contained text as the 'inner' group.
RegExp
#{...} text, returning contained text as the 'inner' group.Exact capture rules:
- Must start with
#{, not part of 'inner' capture group. - Must end with
}, not part of 'inner' capture group. - Named capture group 'inner' within the brackets.
- Must only contain periods, dashes, underscores, unicode letters, and 0-9 digits.
- Must contain at least two unicode letters, or at least one unicode letter and digit.
- Cannot begin or end with a period. Ex.
#{.foo.}not matched. - Cannot start with a digit. Ex.
#{42_digitAtStart}is not matched. - No periods before unicode chars, Ex.
#{_.foo}is not matched. - Two periods cannot be next to one another. Ex.
#{foo.bar}is OK, but#{foo..bar},#{.foo}, and#{foo.}are not. - cannot contain any mix of more than 4 dashes or underscores next to one another. Eg.
#{foo____}and#{-_-_foo-bar_-_-}are OK, but#{--___ foo}and `#{bar----} are not.
Tutorial: https://regex101.com/r/8Bp0Eo/1
convertMS(ms)β object
Convert milliseconds to { days, hours, minutes, seconds } object.
object
| Parameter | Type | Description |
|---|---|---|
| ms | number | milliseconds |
escapeCSS(inputStr, [options])β string
Native CSS.escape() wrapper function that outputs console warnings when inputted CSS string mutates when escaped.
string
CSS.escape() wrapper function that outputs console warnings when inputted CSS string mutates when escaped.Returns: string β escaped CSS
| Parameter | Type |
|---|---|
| inputStr | string |
| [options] | object |
| [options.throwIfEmpty] | boolean |
Categories: helper, devTools
flagEmoji(str)β string
Transform basic ASCII ISO 3166-1 alpha-2 country code strings into 'regional indicator symbol' Unicode sets (aka 'flag Emoji').
string
Returns: string β Unicode regional indicator symbol
| Parameter | Type | Description |
|---|---|---|
| str | string | ISO 3166-1 alpha-2 country code |
Example
ca β π¨π¦
de β π©πͺ
cn β π¨π³
Categories: helper, emoji, string, transformer, unicode
formatTimeAgo(date)β string | false
Returns a localized, relatively formatted date string in the client's inferred locale.
string | false
Returns: string | false β false when date is malformed
Modified version of Kyle Cook's formatter.
| Parameter | Type |
|---|---|
| date | Date |
importLoader(src, [footgun])β Promise.<(Object|function())>
For developer exploring scripts via a live console such as DevTools, especially modules normally hidden from the global scope; how annoying! Scripts are imported into globalThis variables named derived from its file name.
Promise.<(Object|function())>
globalThis variables named derived from its file name.Returns: Promise.<(Object|function())> β import() promise returns requested function or module (object) on success.
Throws: Error β Throws outside 'Development' environment.
This module has no exports, it creates the iL() function under globalThis.
- Multiple exports: module is assigned.
- Single export: single export assigned.
| Parameter | Type | Description |
|---|---|---|
| src | string | '/src/' prepended. |
| [footgun] | string | Accepts a unique string located in this function's source code to bypass environment constraints for live demos and debugging. |
Example
iL('HELPER/slugify.mjs'); // Loads single export module as `slugify()`.
iL('dom/elements.mjs'); // Loads multiple export module as `elements` module.
Categories: devTools, helper
mergeDeep(objects)β object
Perform a deep merge of objects and returns a new object.
object
Returns: object β New object with merged key/values
Doesn't modify objects (immutable) and merges arrays via concatenation. Consider an alternative for advanced merges.
| Parameter | Type | Description |
|---|---|---|
| objects | object | Objects to merge |
simpleHash(str)β number
General-use hash generator.
number
Returns: number β Integer hash (currently CRC24)
Using this for cryptography will result in being shot from a cannon into low earth orbit β¨π (don't use this for cryptographic purposes).
| Parameter | Type |
|---|---|
| str | string |
Categories: helper
slugify(str, [options])β string
'Slugify' a text string.
string
Normally used for URL paths and link anchors.
| Parameter | Type | Description |
|---|---|---|
| str | string | null | undefined | The string to slugify. |
| [options] | object | Configuration options. |
[options.maxSaneLength = 28] | boolean | Strings above this length are chopped and have a hash appended. If modified we recommend keeping the value below 120. |
[options.separator = '-'] | string | Separator character. |
[options.lowercase = true] | boolean | Convert string to lowercase. |
| [options.strict] | boolean | AKA paranoid mode. Removes all non-alphanumeric characters except separators. |
| [options.guaranteeUnique] | boolean | When true this function throws an error instead of a console warning when a duplicate slug is generated (per script instance). |
[options.minSaneLength = 4] | boolean | Strings at or below this threshold generate a console warning. |
Example
slugify('Hello World!') // 'hello-world'
slugify('CafΓ© & Restaurant') // 'cafe-restaurant'
slugify('Multiple Spaces') // 'multiple-spaces'
slugify('--Leading-and-trailing--') // 'leading-and-trailing'
slugify('Hello World', { separator: '_' }) // 'hello_world'
slugify('Hello World', { lowercase: false }) // 'Hello-World'
Categories: helper, string, transformer
namespace modal
activateModal(req)β boolean
Attempt activating a modal element by toggling the active class.
boolean
active class.Returns: boolean β true on success, false when no #modals element is located in the document.
Throws: ReferenceError β When requested modal element doesn't exist.
Modals are contained within an element with the #modals ID.
| Parameter | Type | Description |
|---|---|---|
| req | string | HTML ID attribute of the requested modal element. |
close([_event], [force])β boolean
Attempt closing a modal.
boolean
Returns: boolean β false when no modals exists, no modal is active, or if the modal cannot be closed without force.
This function only closes modals whose first child is a closeBtn button unless the force parameter is true, otherwise the element temporarily gains the attention class. This allows non-critical modals to be closed by pressing on the backdrop.
| Parameter | Type | Description |
|---|---|---|
| [_event] | Event | Currently unused. |
| [force] | boolean | forcibly close modal missing |
currentActiveModalβ HTMLElement | null
Active modal, or null if none.
HTMLElement | null
null if none.Only one modal is active at any given time (assuming nothing broke).
namespace NET
Network related functionality for handling XHR requests, tracking pending requests, and managing network state.
constant pendingREQ object β
Current number of outstanding network requests.
object βDeprecated
Properties
- xhr
numberNumber of active XHR requests
- spinner
numberNumber of active spinner indicators
getResponseHeaderMap(xhr)β Object.<string, string> | Object
Maps XHR response headers into a KV object.
Object.<string, string> | Object
Returns: Object.<string, string> | Object β Empty object when no header values are returned.
| Parameter | Type |
|---|---|
| xhr | XMLHttpRequest |
isLocalPath(src)β boolean
Could src be considered a local path? Domain-like strings WITHOUT protocols (ex. 'example.com') return true as they may be valid local paths.
boolean
src be considered a local path? Domain-like strings WITHOUT protocols (ex. 'example.com') return true as they may be valid local paths.Returns: boolean β True if path is considered local, false otherwise.
Throws: TypeError β When src is not a string.
Returns false when src string begins with a protocol UNLESS it exactly matches window.location.origin.
| Parameter | Type | Description |
|---|---|---|
| src | string | Potential path |
Example
// Assuming origin is https://example.com
// Returns true
isLocalPath('/foo');
isLocalPath('foo.com');
isLocalPath('bar.php');
isLocalPath('foo/bar?fizz#buzz');
isLocalPath('https://example.com');
isLocalPath('https://example.com/foo');
isLocalPath('//example.com'); // `//` matches current protocol, how useful!
// Returns false
isLocalPath('http://example.com'); // mismatched protocol
isLocalPath('https://example.com.evil.org/foo'); // mismatched origin
isLocalPath('javascript:alert("evil")'); // non-http protocol
constant lastIsLocalSrcResult Array.<string, boolean> β
Memoization short circuit for isLocalPath.
Array.<string, boolean> β
isLocalPath.I never checked if this actually improves performance, but it probably helps? It was trivial to implement and just as trivial to remove if deemed unnecessary!
XHRActiveOPsβ number
Current active XHR network requests.
number
xhr(src, [callback], [options])β XMLHttpRequest
Perform an XHR, optionally returning status/object to callback
XMLHttpRequest
Returns: XMLHttpRequest β passes responseObj, src URL to provided callback
- Automatically applies
pd-csrfandpd-app-versionheaders to local requests. - Under
DevelopmentENV thenoStoreoption is true on all local requests to ensure freshness. Create a cookie namedpd-debug-breakLocalCacheto disable this feature.
Why XHR and not Fetch?
- Fetch doesn't track upload progress natively
- Once timeouts, abort controls and other features are added, Fetch feels about the same.
- It's what I knew best when writing PageDriver, feel free to contribute a PR, especially once work begins on ServiceWorkers!
| Parameter | Type | Description |
|---|---|---|
| src | string | Remote URL or local path. Specificity is important! Project's API path is prepended for relative paths NOT starting with a slash |
| [callback] | function | |
| [options] | object | |
[options.type = json] | 'json' | 'head' | 'html' | 'md' | Expected response type. NOT XMLHttpRequest built-in enum, may eventually be extendable via binds. |
[options.spinner = true] | boolean | Request contributes to pending operations UI element (spinner) activation. |
[options.timeout = 10000] | number | Milliseconds, default is 10 seconds |
| [options.formData] | FormData | When included request is sent as 'POST', client's UTC offset and current active PD page are automatically appended (subject to change, provide feedback). |
| [options.noStore] | boolean | Adds request headers to forcibly acquire a fresh response |
| [options.headers] | object | Custom headers |
namespace PAGE
Dynamic page control interface.
The page container element should have nothing except pages as direct descendents. An active page is any direct descendant element of the project's page container with the active class. Theoretically, only one page should be active at any given time.
The first element within the container is considered the site's 'index' (aka home page), located at / and MUST have a valid ID attribute.
Pages may have data-description and data-keywords attributes that are copied to HTML head on activation - dramatically improving SEO. Defaults to SITE description/keywords when not present.
constant pageContainerEl HTMLElement | null
Document's page container element.
HTMLElement | null
body>main, body>#main, body>#pages.
activatePage([pageID], [pushState], [passthrough])β stdReturn
Attempt changing the current active page.
stdReturn
- When successful, the
activeclass is added to the requested page element, the document title, meta description and meta keywords are updated. enteringhelper class istemporarilyadded to the current page element,exitingon the previously active page, if any.- When not permitted (due to context class or inaddequate permissions), the index ID page is activated.
- (EXPERIMENTAL) When not found, the
error-404ID page is activated. MutateserrorMsg. - (EXPERIMENTAL) When a critical error happens during APP initiation , the
error-criticalID page is activated. MutateserrorMsg. - (EXPERIMENTAL) Pages with the
unloadedclass are remote.xhrattempts loading it from/pages/router, which (if successful) calls this function again, replacing element's content and theunloadedclass withremote. This requires server-side framework features.
| Parameter | Type | Description |
|---|---|---|
| [pageID] | string | When undefined we attempt re-activating the current active page; useful in situations when context classes or client permissions may have changed. Denied requests activate the project's index page instead. |
[pushState = true] | boolean | Default true. If true update window title & push a new state to window history stack |
| [passthrough] | object | For unloaded remote pages: ?req=passthrough |
addPage(htmlString, [activate])
Add remote page contents to the document.
| Parameter | Type | Description |
|---|---|---|
| htmlString | string | HTML contents |
| [activate] | boolean | Attempt activating page after mutation |
currentActivePageβ HTMLElement | null
Active page, or null if none.
HTMLElement | null
null if none.Only one page should be active at any given time, thus this only returns the first result. An active page is any direct descendant of the project's page container with the active class.
namespace pd
PageDriver library entry point and global object.
Projects contents:
../app/app.mjsYour project module. PageDriver functionality becomes available withinapp.INIT(), which is executed during initialization.../app/app_settings.mjsfile should be cache friendly and not rely on any PageDriver components. There should be no dynamic elements.- The optional
globalThis.REMOTEobject provides initial dynamic state (such as user data). It is merged and overrides app settings.
Properties: DEBUG
Categories: INIT, client, global
namespace SITE object
object
Properties
- env
'Development'|'Production'Environment.
- [perf]
booleanEnables PageDriver performance monitoring outside 'Debug' mode.
- contexts
Array.<string>Context classes / flags
- [domain =
window.location.hostname]stringAutomatically created during project init.
- [path =
/]stringThis instance's root path.
- api
stringAPI URI, prepended to local API requests.
- title
stringSite title.
- siteTitleFirst
booleanSite title appears first, useful for RTL.
- [titleDivider =
Β·]stringsite and page title separator in window title.
- header
HTMLElementFirst found
headeror#headerelement. - primaryNav
HTMLElementFirst found
nav,#navor#menuelement. - mainRegion
HTMLElementPrimary content region (
body>#main,body>main). - fixedScroll
booleanDoes the
pageselement have fixed scrolling? Is scrolling controlled bypd.SITE.pageselement orwindow? - pages
HTMLCollection#pageschildren. - modals
HTMLCollection#modalschildren. - [remoteReporting]
objectProject's reporting/logging provider. Initialized under 'Production' environment. Create an empty 'pd-forceLogging' cookie to force remote logging outside 'Production' environment. Only Sentry.io is supported at this time.
- remoteReporting.endpoint
URIProvider's reporting endpoint
- remoteReporting.src
URIProvider's bundle location
- [remoteReporting.integrity]
stringSubresource Integrity (SRI) hash, may be required by your CORS settings.
- [remoteReporting.initExtras]
objectOptional properties added to the provider's init. Warning: This can override hardcoded PD options.
- [description]
stringDefault site-wide meta tag. Used when none available at page level.
- [keywords]
stringDefault site meta tag.
module INIT
PageDriver initializer.
The following is out of date, eventually this list will be automatically rendered from inline @steps:
- Debug state check, when the
debugcookie is present load and initialize debug tools. - Begin performance measurement (when enabled).
- Otherwise, execute optional
app.notDebugging()function (to do things such as displaying a default console message/warning)
- Otherwise, execute optional
- Setup remote logging. If
pd.SITE.ENVisProduction, initialize logger based onpd.SITE.remoteReportingobject. Logging can be forcibly enabled viaforceLoggingcookie in other environments. - Set pd.SITE DOM references and booleans
- Context class setup
- i18n initialization
- pd.DOM elements (most removed for upcoming modularity)
- closeable
- Attempt initializing app.js via
app.INIT()(/w perf measurement) - pd.SITE.location
- End performance measurement
- Destroy
pd.INIT
addCloseButton(el)β boolean β
Create a close button ... refactor using future template system...?
boolean β
Returns: boolean β True if closed
| Parameter | Type |
|---|---|
| el | HTMLElement |
module deprecating β
Deprecated
swappable(target) β
Toggle .swapped class on matching elements within local .swappable class node
.swapped class on matching elements within local .swappable class nodeAdds .swapped class to an element with an ID matching the combined target input's name and value (capitalized, if possible), after removing it from its siblings.
Example: Target is a selected radio input named 'eventVis' with the value 'public'. An element with the ID 'eventVisPublic' has .swapped class added, and the class is removed from its siblings.
| Parameter | Type | Description |
|---|---|---|
| target | string | Input element (Checkbox/Radio) |
toggleFUs
Toggle visibility of follow up components
Deprecated
selected
Toggles .selected CSS class on parent element of checked input (checkbox/radio) and toggles related IDs within nearby .swappable element.
.selected CSS class on parent element of checked input (checkbox/radio) and toggles related IDs within nearby .swappable element.Deprecated
If input was added by the user (.userAdded), it is removed from the DOM.
Surround swappable items with a swappable class and give each an ID that is the checkbox/radio name + value with first character capitalized. Ex. a radio named fizz with a value of buzz would trigger an element with the fizzBuzz ID.
Only works if input elements are nested within... 2 elements of each other. Why 2? This functionality was added because I blindly trusted my own HTML, then realized some input elements were unnecessarily nested - now it sits as a reminder to ensure the content you are working with is correct to begin with. Maybe it will come in handy some day.
This trash heap is still necessary in 2021 because CSS doesn't have non-capturing selectors! Why?! WHY CAN'T :has() WORK OUTSIDE OF JS??
module ROUTE
Location routing module.
module perfMark
PageDriver performance marking suite, we recommend using perfMark in components with potentially long run times.
Markings are only recorded when:
- DEBUG mode is active AND/OR
- SITE.perfMark setting boolean is true.
Console output only occurs when the 'DEBUG.verbose.perfMark' flag is enabled.
Example
const perfID = perfMark.start('example');
// ... measured code here
perfMark.end('example',perfID);
start(group, [id])β string | null
Initialize a performance mark with the name format ${group} INIT-${id}.
string | null
${group} INIT-${id}.Returns: string | null β Mark ID or null.
Only functions if device has the performance API, pd.SITE.perfMark is true OR Debug mode is enabled.
| Parameter | Type | Description |
|---|---|---|
| group | string | Human readable grouping string, such as 'app'. |
[id = Math.random] | string | Used as part of the mark's name, randomized by default to prevent duplicates marks when being run multiple times. We recommend changing this to a more human string when only being run once. |
Example
returns `0.8128820578073859` for 'FOO INIT-0.8128820578073859' performance mark.
end(group, id)β number | null
Generate a measurement named ${group} ${id} after creating a mark named ${group} END-${id}.
number | null
${group} ${id} after creating a mark named ${group} END-${id}.Returns: number | null β seconds, rounded to 2 decimal places. null on devices without performance API or with perfMark disabled.
Measurement only outputs console messages when:
- the verbose perfMark debug flag is active
- AND when the measurement is above 3 significant digits (to reduce console spam).
| Parameter | Type | Description |
|---|---|---|
| group | string | |
| id | string | null | Can be null when perfMarking is disabled |
module STORAGE
setCookie(name, [value], [days], [options])
Create, modify, or destroy a cookie.
| Parameter | Type | Description |
|---|---|---|
| name | string | |
| [value] | string | |
| [days] | null | number |
|
| [options] | object | |
[options.samesite = 'strict'] | string | |
[options.hostOnly = true] | string | If true cookie can only be read by the exact domain that set it, not subdomains. Note creating duplicate cookies using both option states breaks things as only one can be managed, PRs welcome. |
[options.path = '/'] | string | Advanced isolation feature. Cookies may behave unexpectedly due to SPA routing. Path must always start with a / slash ...right? |
getCookie(name, [existence])β string | boolean
Get a cookie's value or check for its existence.
string | boolean
Returns: string | boolean β Returns false boolean when non-existent. Returns boolean existence argument is true. Otherwise returns cookie contents string.
| Parameter | Type | Description |
|---|---|---|
| name | string | Cookie name |
| [existence] | boolean | (default false) If true, returns cookie existence boolean, not value - useful for valueless cookies. |
namespace UI
UI Elements
module MENU
User navigation DOM mutators.
activateMenuItem(pathName)
Toggle active class and aria-current on navigation links.
active class and aria-current on navigation links.| Parameter | Type |
|---|---|
| pathName | string |
Categories: DOM, mutator
updateMenu([containerID])β boolean
Mutate primary project navigation from project pages.
boolean
- Pages with the
data-nomenuattribute are ignored. - Transforms the following optional attributes into menu item attributes:
data-descriptionintotitleattribute.data-accesskeyintoaccessKeyattribute.data-iconviaicon.
| Parameter | Type | Description |
|---|---|---|
[containerID = dynamic] | string | Menu element ID |
Categories: DOM, renderer
module mobileMenu
Mobile menu navigation.
Prepend navigation button for collapsing primary navigation on small devices (hamburger π)
Categories: DOM, UI
module relatedElements(target, [composed], [activeClass])β number
Toggles a CSS class on DOM elements related to a form field name/value attribute in the target's element chain, useful for toggling visiblity of elements outside an input element's CSS scope.
number
Returns: number β Total activated elements.
This function finds elements with data-re attributes corresponding to the target's
name and value, then activates matching elements while deactivating others.
- Potential follow up elements are located via the
data-redataset attribute, with a value of the target's name attribute, followed by an underscore[data-re="nameAttr_"]. - Elements exactly matching
[data-re="nameAttr_valueAttr"]and/or[data-re="nameAttr__ANY"]are given the active CSS class. - The active CSS class is removed from non-matching elements.
- When no exact matches are activated, elements matching
[data-re="nameAttr__NONE"]are given the active CSS class. The double underscore is intentional to reduce value collision chance.
Examples:
- Target:
<input name="eventVis" value="public">- Elements with the attributedata-re="eventVis_public"add the active CSS class, whilst all other elements data attributes starting witheventVis_(such aseventVis_private) have the class removed. <option value="0">- The 'name' attribute of a parent<select>is found with the value 'partySize'. No elements with the attributedata-re="partySize_0"were found, so elements with thedata-re="partySize__NONE"add the active CSS class, whilst all other elements withredata classes starting withpartySize_have the active class removed.- (see warning below!)
<input type="checkbox" name="noValue">- Because this input has no value, it will activate elements withdata-re="noValue_on" - (see warning below!)
<option>foobar</option>- Because this input has no value, it will activate elements withdata-re="noValue_foobar"
| Parameter | Type | Description |
|---|---|---|
| target | Element | Any DOM element with |
| [composed] | boolean | Indicates whether the shadow root should be used (false, default), or a root node beyond shadow root (true). |
[activeClass = active] | string | CSS class name toggled on related elements. |
Categories: UI, CSS
constant _META _META
_META
init pdINIT
pdINIT
module UI_toast stdModule
Generate 'pop up' notifications UI elements (aka Toasts) from a cloneable template.
stdModule
Categories: UI, notification, template
makeToast(msg)
Generate a single 'toast' UI element.
| Parameter | Type |
|---|---|
| msg | string |
textarea([height], [width], [minHeight])
Dynamically resize textarea elements to content.
textarea elements to content.// TODO externalized to module? // TODO Output as --pd-textarea-height to allow custom styling?
| Parameter | Type | Description |
|---|---|---|
[height = true] | boolean | When false sets |
| [width] | boolean | |
[minHeight = 50] | number | Minimum fallback height |
addCloseButton(el)β boolean
Create a close button ... refactor using future template system...?
boolean
Returns: boolean β True when closed via local storage
| Parameter | Type |
|---|---|
| el | HTMLElement |
Categories: UI
countdownβ number
Countdown timer UI.
number
Returns: number β Interval ID when activated. Null when element invalid or expired datetime.
appear class temporarily applied to the element on activation. Mutation interval is exactly 1 second.
Properties
- dateTime
dateStringFuture date/time. Accepts anything
new Date()would. - [el =
'#countdown']HTMLElementDefaults to 'countdown' ID element.
- [completedClass =
'complete']stringCompleted CSS class is added when timer expires OR an invalid date is provided.
Categories: UI, timer
spinner(changeState, [el])β number
Pending operation UI (spinner) control.
number
Returns: number β Current pending operations. Cannot be less than 0.
Modifies the --counter variable on the spinner element which can be used to not only hide/reveal the element itself, but dynamically adjust UX - such as the spinner's animation speed.
| Parameter | Type | Description |
|---|---|---|
| changeState | number | Must be exactly 1, 0, or -1. Zero returns current number of pending operations without modifying state. |
[el = document.getElementById('spinner')] | HTMLElement | (EXPERIMENT) Change default target spinner element (#spinner) |
Categories: UI, DOM
typedef _META object
PageDriver standardized metadata property.
object
Properties
- name
stringHuman readable project/module name. Used by error reporter.
- [stable =
1]0|1|1.1|1.2|2|3Copies the NodeJS stability index.
- 0 - Deprecated. The feature may emit warnings. Backward compatibility is not guaranteed.
- 1 - Experimental. The feature is not subject to semantic versioning rules. Non-backward compatible changes or removal may occur in any future release. Use of the feature is not recommended in production environments. Experimental features leave the experimental status typically either by graduating to stable, or are removed without a deprecation cycle. Experimental features are subdivided into stages:
- 1.0 - Early development. Experimental features at this stage are unfinished and subject to substantial change.
- 1.1 - Active development. Experimental features at this stage are nearing minimum viability.
- 1.2 - Release candidate. Experimental features at this stage are hopefully ready to become stable. No further breaking changes are anticipated but may still occur in response to user feedback. We encourage user testing and feedback so that we can know that this feature is ready to be marked as stable.
- 2 - Stable. Compatibility with the PageDriver ecosystem is a high priority.
- 3 - Legacy. Although this feature is unlikely to be removed and is still covered by semantic versioning guarantees, it is no longer actively maintained, and other alternatives are available.
- version
semverSemantic versioning code, see https://semver.org/.
- [changelog =
'/changelog.md']stringURL or local path.
- [compliance]
Array.<string>['i18n-AA','a11y-AA','GDPR']... - [license]
stringSoftware license shortname. ex. 'Apache-2.0'
- [category]
Array.<string>Taxonomy, comma delimited categorization for documentation and reference lookups. First one listed could be considered 'primary'.
- [stage]
'1-Discuss'|'1-Needs_champion'|'2-WIP'|'2-Feedback_needed'|'3-Test'|'4-Document'|'5-Shipped'|'6-Needs_Refactor_or_Deprecation'Current production stage. This doesn't really belong in _META, but some sort of JSDOC/Typedoc metadoc? Should match PageDriver's own 'flow' labels closely.
- edition
'CORE'|'PRO'|'PLATFORM'Target edition.
- [authors]
Array.<UUIDv4>(CONCEPT)
- [targets]
Array.<'Client', 'Server', 'Platform'>Relevant domains.
- C Client / Browser / Front-end
- S Server-side / Edge
- P PageDriver Platform.
- [parallel]
boolean(CONCEPT) 'Multi-thread' / parallelization safe. Workers? π€
- [priority]
number(CONCEPT) Loading prioritization? idk
typedef stdModule object
PageDriver standard module.
object
Properties
- [_META]
_META - INIT
function - [boundInterface]
BindInterfaceInstantiate via
initBindInterface.
typedef stdReturn object
Pagedriver standardized return object.
object
Properties
- status
numberStatus code
0Pending1Partial success (see errors)2Success-1Aborted-2Failure (see errors)
- [result]
objectGeneric return object. This is where your custom return data goes.
- [log]
objectRequired when
statusis 1 (partial success) or -2 (failure). - [log.errors]
Array.<PDLog> - [log.warnings]
Array.<PDLog> - [stats]
object(EXPERIMENT) Optional operational statistics. Ex. bind stats (added/runs/disabled). Likely to be moved to dedicated stats/analytics module. Feedback welcome.
typedef PDLog object
Standard error response
object
Properties
- code
stringStable error code for i18n (e.g., 'ERR_MAX_DEPTH')
- [message]
stringFallback English message
- [context]
objectData for i18n interpolation
- [path]
Array.<string>Location in data structure where error occurred
- [details]
*Additional error-specific information