### Install @dojo/cli-create-theme
Source: https://github.com/dojo/framework/blob/master/docs/en/styling/supplemental.md
Install the theme scaffolding tool as a development dependency in your project.
```bash
npm install --save-dev @dojo/cli-create-theme
```
--------------------------------
### Example Widget Using Resize Middleware
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
A sample widget that utilizes the resize middleware to get content rects for a 'root' element.
```tsx
import {
create,
tsx
} from '@dojo/framework/core/vdom';
import resize from '@dojo/framework/core/middleware/resize';
const factory = create({ resize });
export const MyWidget = factory(function MyWidget({ middleware }) {
const { resize } = middleware;
const contentRects = resize.get('root');
return
{JSON.stringify(contentRects)}
;
});
```
--------------------------------
### Get Operation Example
Source: https://github.com/dojo/framework/blob/master/docs/en/stores/introduction.md
Shows how to retrieve a value from the store using a specified path. It also demonstrates conditional logic based on the retrieved value, potentially removing state if a token is absent.
```typescript
import { createCommandFactory } from '@dojo/framework/stores/process';
import { State } from './interfaces';
import { remove, replace } from '@dojo/framework/stores/state/operations';
const createCommand = createCommandFactory();
const updateCurrentUser = createCommand(async ({ at, get, path }) => {
const token = get(path('auth', 'token'));
if (!token) {
return [remove(path('users', 'current'))];
} else {
const user = await fetchCurrentUser(token);
return [replace(path('users', 'current'), user)];
}
});
```
--------------------------------
### Date, Number, and Unit Formatting Examples
Source: https://github.com/dojo/framework/blob/master/docs/en/i18n/supplemental.md
Demonstrates the usage of date, number, and unit formatters for different locales. Includes examples for formatting dates, relative times, currencies, and units with various options.
```typescript
import { formatDate, getDateFormatter, formatRelativeTime } from '@dojo/framework/i18n/date';
import { formatCurrency, getCurrencyFormatter } from '@dojo/framework/i18n/number';
import { formatUnit, getUnitFormatter } from '@dojo/framework/i18n/unit';
const date = new Date(1815, 11, 10, 11, 27);
// Assume the current locale is "en"
const enDateFormatter = getDateFormatter({ datetime: 'medium' });
enDateFormatter(date); // Dec 10, 1815, 11:27:00 AM
formatDate(date, { date: 'short' }); // 12/10/15
const frDateFormatter = getDateFormatter({ datetime: 'medium' }, 'fr');
frDateFormatter(date); // 10 déc. 1815 à 11:27:00
formatDate(date, { date: 'short' }, 'fr'); // 10/12/1815
formatRelativeTime(-1, 'week'); // "last week"
formatRelativeTime(-1, 'week', { form: 'short' }); // "last wk."
formatRelativeTime(-3, 'week', null, 'fr'); // "il y a 3 semaines"
formatRelativeTime(-3, 'week', { form: 'short' }, 'fr'); // "il y a 3 sem."
const enCurrencyFormatter = getCurrencyFormatter('USD', { style: 'code' });
enCurrencyFormatter(1234.56); // "1,234.56 USD"
formatCurrency(12345.56, 'USD', { style: 'code' }); // "1,234.56 USD"
const frCurrencyFormatter = getCurrencyFormatter('EUR', { style: 'code' }, 'fr');
frCurrencyFormatter(1234.56); // "1 234,56 EUR"
formatCurrency(12345.56, 'EUR', { style: 'code' }, 'fr'); // "1 234,56 EUR"
const enUnitFormatter = getUnitFormatter('feet', { form: 'narrow' });
enUnitFormatter(5280); // 5,280′
formatUnit(5280, 'feet', { form: 'narrow' }); // 5,280′
const frUnitFormatter = getUnitFormatter('meter', null, 'fr');
frUnitFormatter(1000); // 1 000 mètres'
formatUnit(1000, 'meter', null, 'fr); // 1 000 mètres'
```
--------------------------------
### Install CLI Build Theme Package
Source: https://github.com/dojo/framework/blob/master/docs/en/styling/supplemental.md
Install the `@dojo/cli-build-theme` package as a development dependency in your theme project.
```bash
npm install --save-dev @dojo/cli-build-theme
```
--------------------------------
### Custom Middleware Mock Factory Example
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
This example illustrates how to create a custom middleware mock, providing both the middleware implementation for the widget and a test interface for controlling its behavior.
```ts
export function createMockMiddleware() {
const sharedData = new Map();
const mockFactory = factory(() => {
// actual middleware implementation; uses `sharedData` to bridge the gap
return {
get(id: string): any {},
set(id: string, value: any): void {}
};
});
function mockMiddleware(): MiddlewareResult;
function mockMiddleware(id: string): any;
function mockMiddleware(id?: string): any | Middleware {
if (id) {
// expose access to `sharedData` directly to
return sharedData.get(id);
} else {
// provides the middleware implementation to the widget
return mockFactory();
}
}
}
```
--------------------------------
### Resource Template and User Interface Example
Source: https://github.com/dojo/framework/blob/master/docs/en/resources/supplemental.md
Imports the `createResourceTemplate` and defines a sample `User` interface for resource data.
```typescript
import { createResourceTemplate } from '@dojo/framework/core/middleware/resources';
interface User {
firsName: string;
lastName: string;
username: string;
email: string;
}
```
--------------------------------
### Create a Basic Widget
Source: https://github.com/dojo/framework/blob/master/docs/en/ref-guide-template/basic-usage.md
Demonstrates how to create a simple Dojo widget using WidgetBase and tsx for rendering. This is a foundational example for building UI components.
```tsx
// fully working & copy/paste-able sample code content...
import WidgetBase from '@dojo/framework/core/WidgetBase';
import { tsx } from '@dojo/framework/core/vdom';
export default class MyWidget extends WidgetBase {
protected render() {
return
My Widget
;
}
}
```
--------------------------------
### Before Middleware Example
Source: https://github.com/dojo/framework/blob/master/src/stores/README.md
Applies 'before' callbacks to a process. Callbacks are executed in the order they are provided.
```typescript
const myProcess = createProcess('my-process', [commandOne, commandTwo], [authenticator, logger]);
```
--------------------------------
### Serve and Watch Application
Source: https://github.com/dojo/framework/blob/master/docs/en/building/introduction.md
Use this command to start a development server that serves the application and automatically rebuilds it when files change. The application is served on port 9999 by default.
```bash
> dojo build --mode dev --watch --serve
```
--------------------------------
### Focus Delegation Example
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Example demonstrating how to delegate and control focus across a widget hierarchy using the focus middleware. The child input's onfocus event handler is passed from the parent to propagate focus changes.
```tsx
import { create, tsx } from '@dojo/framework/core/vdom';
import focus from '@dojo/framework/core/middleware/focus';
import icache from '@dojo/framework/core/middleware/icache';
/*
The input's `onfocus()` event handler is assigned to a method passed in
from a parent widget, via the child's create().properties
API, allowing user-driven focus changes to propagate back into the application.
*/
const childFactory = create({ focus }).properties<{ onfocus: () => void }>();
const FocusInputChild = childFactory(function FocusInputChild({ middleware: { focus }, properties }) {
const { onfocus } = properties();
return ;
});
const factory = create({ focus, icache });
export default factory(function FocusableWidget({ middleware: { focus, icache } }) {
const keyWithFocus = icache.get('key-with-focus') || 0;
const childCount = 5;
function focusPreviousChild() {
let newKeyToFocus = (icache.get('key-with-focus') || 0) - 1;
if (newKeyToFocus < 0) {
newKeyToFocus = childCount - 1;
}
icache.set('key-with-focus', newKeyToFocus);
focus.focus();
}
function focusNextChild() {
let newKeyToFocus = (icache.get('key-with-focus') || 0) + 1;
if (newKeyToFocus >= childCount) {
newKeyToFocus = 0;
}
icache.set('key-with-focus', newKeyToFocus);
focus.focus();
}
function focusChild(key: number) {
icache.set('key-with-focus', key);
focus.focus();
}
return (
);
});
```
--------------------------------
### Creating and Executing a Process
Source: https://github.com/dojo/framework/blob/master/docs/en/stores/introduction.md
Shows how to define a process that sequentially executes asynchronous commands. This example fetches a user token and then loads user data using that token.
```typescript
import { createCommandFactory, createProcess } from "@dojo/framework/stores/process";
import { State } from './interfaces';
import { add, replace } from "@dojo/framework/stores/state/operations";
const createCommand = createCommandFactory();
const fetchUser = createCommand(async ({ at, get, payload: { username, password } }) => {
const token = await fetchToken(username, password);
return [
add(path('auth', 'token'), token);
];
}
const loadUserData = createCommand(async ({ path }) => {
const token = get(path('auth', 'token'));
const user = await fetchCurrentUser(token);
return [
replace(path('users', 'current'), user)
];
});
export const login = createProcess('login', [ fetchUser, loadUserData ]);
```
--------------------------------
### Custom Breakpoint Middleware Example
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Example of creating a custom breakpoint middleware with specific default breakpoints.
```APIDOC
```ts
import { createBreakpointMiddleware } from '@dojo/framework/core/middleware/breakpoint';
const myCustomBreakpoint = createBreakpointMiddleware({ Narrow: 0, Wide: 500 });
export default myCustomBreakpoint;
```
```
--------------------------------
### Class-based Widget Focus Delegation Example
Source: https://github.com/dojo/framework/blob/master/docs/en/creating-widgets/supplemental.md
Demonstrates how to use FocusMixin to delegate focus to child input elements and manage focus changes via parent widget logic. This example shows controlling focus through 'Previous' and 'Next' buttons.
```tsx
import WidgetBase from '@dojo/framework/core/WidgetBase';
import { tsx } from '@dojo/framework/core/vdom';
import Focus from '@dojo/framework/core/mixins/Focus';
interface FocusInputChildProperties {
onFocus: () => void;
}
class FocusInputChild extends Focus(WidgetBase) {
protected render() {
/*
The child widget's `this.shouldFocus()` method is assigned directly to the
input node's `focus` property, allowing focus to be delegated from a higher
level containing parent widget.
The input's `onfocus()` event handler is also assigned to a method passed
in from a parent widget, allowing user-driven focus changes to propagate back
into the application.
*/
return ;
}
}
export default class FocusableWidget extends Focus(WidgetBase) {
private currentlyFocusedKey = 0;
private childCount = 5;
private onFocus(key: number) {
this.currentlyFocusedKey = key;
this.invalidate();
}
/*
Calling `this.focus()` resets the widget so that `this.shouldFocus()` will return true when it is next invoked.
*/
private focusPreviousChild() {
--this.currentlyFocusedKey;
if (this.currentlyFocusedKey < 0) {
this.currentlyFocusedKey = this.childCount - 1;
}
this.focus();
}
private focusNextChild() {
++this.currentlyFocusedKey;
if (this.currentlyFocusedKey === this.childCount) {
this.currentlyFocusedKey = 0;
}
this.focus();
}
protected render() {
/*
The parent widget's `this.shouldFocus()` method is passed to the relevant child element
that requires focus, based on the simple previous/next widget selection logic.
This allows focus to be delegated to a specific child node based on higher-level logic in
a container/parent widget.
*/
return (
);
}
}
```
--------------------------------
### Example Query Parameters Object
Source: https://github.com/dojo/framework/blob/master/docs/en/routing/supplemental.md
Illustrates the structure of the queryParams object based on a URL.
```javascript
{
foo: 'bar',
baz: '42'
}
```
--------------------------------
### Example Path Parameters Object
Source: https://github.com/dojo/framework/blob/master/docs/en/routing/supplemental.md
Shows the params object containing extracted path parameters from a URL.
```javascript
{
page: 'about';
}
```
--------------------------------
### Create a new theme
Source: https://github.com/dojo/framework/blob/master/docs/en/styling/supplemental.md
Use the `dojo create theme` command to start scaffolding a new theme for third-party widgets. Replace `{myThemeName}` with your desired theme name.
```bash
dojo create theme -n {myThemeName}
```
--------------------------------
### After Middleware Example
Source: https://github.com/dojo/framework/blob/master/src/stores/README.md
Applies 'after' callbacks to a process. Callbacks are executed in the order they are provided.
```typescript
const myProcess = createProcess('my-process', [commandOne, commandTwo], [callback, logger, snapshot]);
```
--------------------------------
### Create a Simple Process (TypeScript)
Source: https://github.com/dojo/framework/blob/master/src/stores/README.md
A `Process` executes commands sequentially against a store. Use `createProcess` with an array of commands. This example creates a process to add a todo and recalculate counts.
```typescript
const addTodoProcess = createProcess('add-todo', [addTodoCommand, calculateCountCommand]);
```
--------------------------------
### Route Configuration Example
Source: https://github.com/dojo/framework/blob/master/src/routing/README.md
Defines a hierarchical structure for application routes, mapping paths to specific outlets. Includes nested routes and their corresponding outlet keys.
```typescript
import { RouteConfig } from '@dojo/framework/routing/interfaces';
const config: RouteConfig[] = [
{
path: 'foo',
outlet: 'root',
children: [
{
path: 'bar',
outlet: 'bar'
},
{
path: 'baz',
outlet: 'baz',
children: [
{
path: 'qux',
outlet: 'qux'
}
]
}
]
}
];
```
--------------------------------
### Define Routing Configuration
Source: https://github.com/dojo/framework/blob/master/docs/en/routing/introduction.md
Configure routes for your application. This example shows a basic structure with nested routes, essential for code splitting.
```ts
export default [
{
id: 'home',
path: 'home',
outlet: 'home'
},
{
id: 'about',
path: 'about',
outlet: 'about',
children: [
{
id: 'company',
path: 'company',
outlet: 'about-company'
}
]
},
{
id: 'profile',
path: 'profile',
outlet: 'profile'
},
{
id: 'settings',
path: 'settings',
outlet: 'settings'
}
];
```
--------------------------------
### Additional Widget Example
Source: https://github.com/dojo/framework/blob/master/docs/en/ref-guide-template/basic-usage.md
Provides additional sample code for widget development, potentially illustrating related concepts or variations.
```tsx
// more sample file code content, likely referring to other files in the same feature example ...
```
--------------------------------
### Configure PWA Manifest in .dojorc
Source: https://github.com/dojo/framework/blob/master/docs/en/building/supplemental.md
Define PWA manifest properties within the `.dojorc` file to enable installation on devices. This includes application name, description, and icons.
```json
{
"build-app": {
"pwa": {
"manifest": {
"name": "Todo MVC",
"description": "A simple to-do application created with Dojo",
"icons": [
{ "src": "./favicon-16x16.png", "sizes": "16x16", "type": "image/png" },
{ "src": "./favicon-32x32.png", "sizes": "32x32", "type": "image/png" },
{ "src": "./favicon-48x48.png", "sizes": "48x48", "type": "image/png" },
{ "src": "./favicon-256x256.png", "sizes": "256x256", "type": "image/png" }
]
}
}
}
}
```
--------------------------------
### Making a GET Request
Source: https://github.com/dojo/framework/blob/master/docs/core/request.md
Use this method to perform a simple GET request. It returns a promise that resolves with the response, which can then be processed, for example, by parsing it as JSON.
```typescript
const json = await request('http://www.example.com').then((response) => response.json());
```
--------------------------------
### TSX Widget Example (Function-based)
Source: https://github.com/dojo/framework/blob/master/docs/en/creating-widgets/supplemental.md
Demonstrates a simple function-based Dojo widget using TSX syntax for its VDOM output. Requires importing `create` and `tsx` from `@dojo/framework/core/vdom`.
```tsx
import { create, tsx } from '@dojo/framework/core/vdom';
const factory = create();
export default factory(function MyTsxWidget() {
return
Hello from a TSX widget!
;
});
```
--------------------------------
### Define Routes with Outlets
Source: https://github.com/dojo/framework/blob/master/docs/en/routing/supplemental.md
Configure routes to specify which outlet should render their content. This example shows how 'main' and 'side-menu' outlets are used for different route segments.
```tsx
const routes = [
{
id: 'landing',
path: '/',
outlet: 'main',
defaultRoute: true
},
{
id: 'widget',
path: 'widget/{widget}',
outlet: 'side-menu',
children: [
{
id: 'tests',
path: 'tests',
outlet: 'main'
},
{
id: 'overview',
path: 'overview',
outlet: 'main'
},
{
id: 'example'
path: 'example/{example}',
outlet: 'main'
}
]
}
];
```
--------------------------------
### Function-based Widget with icache Middleware
Source: https://github.com/dojo/framework/blob/master/docs/en/creating-widgets/supplemental.md
Use the `icache` middleware to manage local state and automatically invalidate the widget when state is updated. This example demonstrates setting and getting state within the widget.
```tsx
import { create, tsx } from '@dojo/framework/core/vdom';
import icache from '@dojo/framework/core/middleware/icache';
const factory = create({ icache });
export default factory(function MyEncapsulatedStateWidget({ middleware: { icache } }) {
return (
Current widget state: {icache.getOrSet('myState', 'Hello from a stateful widget!')}
);
});
```
--------------------------------
### Asynchronous Command Example
Source: https://github.com/dojo/framework/blob/master/src/stores/README.md
Demonstrates an asynchronous command that returns a Promise of PatchOperations. This is achieved by using an async function and awaiting asynchronous operations like fetch.
```typescript
async function postTodoCommand({ get, path, payload: { id } }: CommandRequest): Promise {
const response = await fetch('/todos');
if (!response.ok) {
throw new Error('Unable to post todo');
}
const json = await response.json();
const todos = get(path('todos'));
const index = findIndex(todos, byId(id));
// success
return [
replace(at(path('todos'), index), {
...todos[index],
loading: false,
id: data.uuid
})
];
}
```
--------------------------------
### Create Production Build
Source: https://github.com/dojo/framework/blob/master/docs/en/building/introduction.md
Run this command to create an optimized build for production. The build will use the 'dist' mode and output results to the 'output/dist' directory.
```bash
> dojo build --mode dist
```
--------------------------------
### Dojo AMD Configuration and Initialization
Source: https://github.com/dojo/framework/blob/master/tests/core/benchmark/app/index.html
Configures the AMD loader with shim dependencies and initializes the benchmark application's main module. This is the entry point for the benchmark app.
```javascript
require.config(shimAmdDependencies({ baseUrl: '../../../../../../' })); require(['dist/dev/src/shim/main'], function() { require(['dist/dev/tests/core/benchmark/app/main'], function () {}); });
```
--------------------------------
### Create a Simple Middleware
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Defines a basic middleware with `get()` and `set()` methods using the `create()` factory. This is useful for encapsulating state or logic that needs to be shared across widgets.
```typescript
import { create } from '@dojo/framework/core/vdom';
const factory = create();
export const myMiddleware = factory(() => {
return {
get() {},
set() {}
};
});
export default myMiddleware;
```
--------------------------------
### get function
Source: https://github.com/dojo/framework/blob/master/docs/en/stores/introduction.md
The `get` function retrieves a value from the store at a specified path. If no value exists at the location, it returns `undefined`.
```APIDOC
## get function
### Description
The `get` function returns a value from the store at a specified path or `undefined` if a value does not exist at that location.
### Usage
```ts
import { createCommandFactory } from '@dojo/framework/stores/process';
import { State } from './interfaces';
import { remove, replace } from '@dojo/framework/stores/state/operations';
const createCommand = createCommandFactory();
const updateCurrentUser = createCommand(async ({ at, get, path }) => {
const token = get(path('auth', 'token'));
if (!token) {
return [remove(path('users', 'current'))];
} else {
const user = await fetchCurrentUser(token);
return [replace(path('users', 'current'), user)];
}
});
```
### Example
This example checks for the presence of an authentication token and works to update the current user information.
```
--------------------------------
### GET Request
Source: https://github.com/dojo/framework/blob/master/docs/core/request.md
Sends an HTTP GET request to the specified URL. The response is returned as a promise that resolves with the response object.
```APIDOC
## GET Request
### Description
Sends an HTTP GET request to the specified URL. The response is returned as a promise that resolves with the response object.
### Method
GET
### Endpoint
[URL]
### Parameters
#### Query Parameters
- **url** (string) - Required - The URL to send the request to.
### Request Example
```typescript
const json = await request('http://www.example.com').then((response) => response.json());
```
### Response
#### Success Response (200)
- **response** (object) - The response object from the HTTP request.
#### Response Example
```json
{
"example": "response body"
}
```
```
--------------------------------
### Themeable Widget with Multiple CSS Modules
Source: https://github.com/dojo/framework/blob/master/docs/en/styling/supplemental.md
Extends the themeable widget example to import and use multiple CSS modules, combining base styles with widget-specific styles.
```typescript
import { create, tsx } from '@dojo/framework/core/vdom';
import theme from '@dojo/framework/core/middleware/theme';
import * as css from '../styles/MyThemeableWidget.m.css';
import * as commonCss from '../styles/MyThemeCommonStyles.m.css';
const factory = create({ theme });
export default factory(function MyThemeableWidget({ middleware: { theme } }) {
const { root } = theme.classes(css);
const { commonBase } = theme.classes(commonCss);
return (
Hello from a themed Dojo widget!
);
});
```
--------------------------------
### Create and Configure Resize Mock
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
Demonstrates how to create a mock resize middleware and set its expected return values for a specific key.
```typescript
const mockResize = createResizeMock();
mockResize('key', { width: 100 });
```
--------------------------------
### Get Meta Information with Default Behavior
Source: https://github.com/dojo/framework/blob/master/docs/en/resources/supplemental.md
Demonstrates how to get meta information for current options without initiating a request. This snippet is useful when you only need to check existing metadata.
```tsx
import { create, tsx } from '@dojo/framework/core/vdom';
import { createResourceMiddleware } from '@dojo/framework/core/middleware/resources';
const resource = createResourceMiddleware<{ value: string }>();
const factory = create({ resource });
export default factory(function MyDataAwareWidget({ id, properties, middleware: { resource } }) {
const { meta, createOptions } = resource;
const {
resource: { template, options = createOptions(id) }
} = properties();
// get the meta info for the current options
const metaInfo = meta(template, options());
if (metaInfo && metaInfo.total > 0) {
// do something if there is a known total
}
});
```
--------------------------------
### Get the first value for a key in UrlSearchParams
Source: https://github.com/dojo/framework/blob/master/docs/core/UrlSearchParams.md
Use the `get` method to retrieve the first value associated with a given key. If the key has multiple values, only the first one is returned.
```typescript
import { UrlSearchParams } from '@dojo/framework/core/UrlSearchParams';
const searchParams = new UrlSearchParams('a=first&a=second');
const key = 'a';
const result = searchParams.get(key);
result === 'first'; // true
```
--------------------------------
### Run Tests with TestingBot via Command Line
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
Configure TestingBot credentials using command-line arguments for key and secret. Sign up for a TestingBot account to obtain these.
```bash
dojo test -a -c testingbot -k -s
```
--------------------------------
### Array fill
Source: https://github.com/dojo/framework/blob/master/docs/shim/array.md
Fills all elements in an array with a static value, from a specified start index up to (but not including) a specified end index. If start or end are omitted, they default to 0 and the array length respectively.
```ts
import { fill } from '@dojo/framework/shim/array';
var array = [0, 1, 2, 3];
var start = 1; // the starting index to fill
var end = 4; // the ending index (exclusive) to stop filling
fill(array, 4, start, end);
array[0] === 0; // true
array[1] === 4; // true
array[2] === 4; // true
array[3] === 4; // true
```
--------------------------------
### Mock Store Middleware with Process Stubbing
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
Demonstrates how to create a typed mock store middleware, optionally stubbing original processes with provided stub processes. Unstubbed processes are ignored. Use `mockStore` to apply operations to the mock store.
```tsx
mockStore((path) => [
replace(path('details', { id: 'id' }))
]);
```
```tsx
import { tsx } from '@dojo/framework/core/vdom'
import createMockStoreMiddleware from '@dojo/framework/testing/mocks/middleware/store';
import renderer from '@dojo/framework/testing/renderer';
import { myProcess } from './processes';
import MyWidget from './MyWidget';
import MyState from './interfaces';
import store from './store';
// import a stub/mock lib, doesn't have to be sinon
import { stub } from 'sinon';
describe('MyWidget', () => {
it('test', () => {
const properties = {
id: 'id'
};
const myProcessStub = stub();
// type safe mock store middleware
// pass through an array of tuples `[originalProcess, stub]` for mocked processes
// calls to processes not stubbed/mocked get ignored
const mockStore = createMockStoreMiddleware([[myProcess, myProcessStub]]);
const r = renderer(() => , {
middleware: [[store, mockStore]]
});
r.expect(/* assertion for `Loading`*/);
// assert again the stubbed process
expect(myProcessStub.calledWith({ id: 'id' })).toBeTruthy();
mockStore((path) => [replace(path('isLoading', true))]);
r.expect(/* assertion for `Loading`*/);
expect(myProcessStub.calledOnce()).toBeTruthy();
// use the mock store to apply operations to the store
mockStore((path) => [replace(path('details', { id: 'id' }))]);
mockStore((path) => [replace(path('isLoading', true))]);
r.expect(/* assertion for `ShowDetails`*/);
properties.id = 'other';
r.expect(/* assertion for `Loading`*/);
expect(myProcessStub.calledTwice()).toBeTruthy();
expect(myProcessStub.secondCall.calledWith({ id: 'other' })).toBeTruthy();
mockStore((path) => [replace(path('details', { id: 'other' }))]);
r.expect(/* assertion for `ShowDetails`*/);
});
});
```
--------------------------------
### padStart
Source: https://github.com/dojo/framework/blob/master/docs/shim/string.md
Pads the current string with a given string (repeated, if needed) so that the resulting string reaches a given length.
```APIDOC
## `padStart`
### Description
Adds padding to the beginning of a string to ensure it is a certain length.
### Parameters
- **str** (string) - The string to pad.
- **length** (number) - The target length of the resulting string.
- **padString** (string, optional) - The string to pad with. Defaults to a space character (' ').
### Returns
(string) - The padded string.
### Example
```ts
import { padStart } from '@dojo/framework/shim/string';
const str = 'string';
const length = 10;
const char = '=';
const result = padStart(str, length, char);
console.log(result); // Output: "====string"
```
```
--------------------------------
### Access Store Data in a Functional Widget
Source: https://github.com/dojo/framework/blob/master/docs/en/stores/introduction.md
In a functional widget, use the `store` middleware to access and display data from the store. This involves getting the store instance and using `get` with `path` to retrieve specific state values.
```tsx
import { create } from '@dojo/framework/core/vdom';
import store from '../middleware/store';
import { State } from '../../interfaces';
const factory = create({ store }).properties();
export const User = factory(function User({ middleware: { store } }) {
const { get, path } = store;
const name = get(path('users', 'current', 'name'));
return
{`Hello, ${name}`}
;
});
```
--------------------------------
### Build a Dojo Theme
Source: https://github.com/dojo/framework/blob/master/docs/en/styling/supplemental.md
Use the `dojo build theme` command to build a theme for distribution. Specify the theme name and an optional release version. If no release version is provided, the version from `package.json` will be used.
```bash
dojo build theme --name={myThemeName} --release={releaseVersion}
```
--------------------------------
### Resource-Aware Widget Example
Source: https://github.com/dojo/framework/blob/master/docs/en/resources/supplemental.md
This snippet demonstrates a basic resource-aware widget that fetches and displays a list of items. It uses `createResourceMiddleware` to manage resource data and `getOrRead` to fetch items based on a template and options. The widget handles a loading state when data is not yet available.
```tsx
import { create, tsx } from '@dojo/framework/core/vdom';
import { createResourceMiddleware } from '@dojo/framework/core/middleware/resources';
interface ResourceData {
value: string;
label: string;
}
const resource = createResourceMiddleware();
const factory = create({ resource });
export default factory(function MyDataAwareWidget({ id, properties, resource }) {
const { getOrRead, createOptions } = resource;
const {
resource: { template, options = createOptions(id) }
};
const [items] = getOrRead(template, options());
if (!items) {
return
Loading...
;
}
return
{items.map((item) =>
{item.label}
)}
;
});
```
--------------------------------
### Instantiating Widget with Middleware Properties
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Shows how to instantiate a widget that uses middleware with properties, specifying the property value during widget creation.
```tsx
import renderer, { tsx } from '@dojo/framework/core/vdom';
import MiddlewarePropertiesWidget from './widgets/MiddlewarePropertiesWidget';
const r = renderer(() => );
r.mount();
```
--------------------------------
### get
Source: https://github.com/dojo/framework/blob/master/docs/core/UrlSearchParams.md
Retrieves the first value associated with a given key.
```APIDOC
## get
### Description
Retrieves the first value for the key provided.
### Method
`get(key: string): string | null`
### Parameters
#### Path Parameters
- None
#### Query Parameters
- None
#### Request Body
- None
### Response
#### Success Response
- Returns the first associated value as a string, or null if the key is not found.
### Usage
```javascript
import { UrlSearchParams } from '@dojo/framework/core/UrlSearchParams';
const searchParams = new UrlSearchParams('a=first&a=second');
const key = 'a';
const result = searchParams.get(key);
result === 'first'; // true
```
```
--------------------------------
### Define Widgets and Injectors with Registry
Source: https://github.com/dojo/framework/blob/master/src/core/README.md
Demonstrates how to create a new Registry instance, define a widget, and define an injector. The renderer is then configured with this registry.
```typescript
import { Registry } from '@dojo/framework/core/Registry';
import { w } from '@dojo/framework/core/vdom';
import MyWidget from './MyWidget';
import MyAppContext from './MyAppContext';
import App from './App';
const registry = new Registry();
registry.define('my-widget', MyWidget);
registry.defineInjector('my-injector', (invalidator) => {
const appContext = new MyAppContext(invalidator);
return () => appContext;
});
const r = renderer(() => w(App, {}));
r.registry = registry;
```
--------------------------------
### Breakpoint Widget Example
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
A widget that displays an H2 when the LG breakpoint is active.
```tsx
import { tsx, create } from '@dojo/framework/core/vdom';
import breakpoint from '@dojo/framework/core/middleware/breakpoint';
const factory = create({ breakpoint });
export default factory(function Breakpoint({ middleware: { breakpoint } }) {
const bp = breakpoint.get('root');
const isLarge = bp && bp.breakpoint === 'LG';
return (
Header
{isLarge &&
Subtitle
}
Longer description
);
});
```
--------------------------------
### Default Language Bundle Example
Source: https://github.com/dojo/framework/blob/master/docs/en/i18n/supplemental.md
Defines the default messages for a language bundle.
```ts
export default {
messages: {
hello: 'Welcome to the shop',
purchaseItems: 'Please confirm your purchase',
itemCount: 'Purchase {count} items'
}
};
```
--------------------------------
### Set Up Upstream Repository
Source: https://github.com/dojo/framework/blob/master/CONTRIBUTING.md
Add the official dojo/framework repository as a remote named 'upstream' to fetch changes from the main project.
```bash
cd dojo-framework
git remote add upstream git@github.com:dojo/framework.git
git fetch upstream
```
--------------------------------
### Loading a resource using a plugin
Source: https://github.com/dojo/framework/blob/master/docs/core/load.md
Demonstrates how to load a resource using an AMD-style plugin. The process involves loading the plugin, normalizing the resource ID, and then loading the resource via the plugin's 'load' method.
```typescript
import load from '@dojo/framework/core/load';
// 1. The module with the id `plugin` is loaded.
// 2. If `plugin` is not actually a plugin, then `plugin` itself is returned.
// 3. If the plugin has a normalize method, then "some/resource/id" is passed to it,
// and the return value is used as the resource id.
// 4. The resource id is passed to the plugin's `load` method.
// 5. The loaded resource is used to resolve the `load` promise.
load('plugin!some/resource/id').then(([resource]: [any]) => {
// ...
});
```
--------------------------------
### Basic Widget Implementation
Source: https://github.com/dojo/framework/blob/master/docs/en/ref-guide-template/supplemental.md
Illustrates a fundamental widget structure using WidgetBase and tsx for rendering.
```tsx
import WidgetBase from '@dojo/framework/core/WidgetBase';
import { tsx } from '@dojo/framework/core/vdom';
export default class MyWidget extends WidgetBase {
protected render() {
return
My Widget
;
}
}
```
--------------------------------
### Run Project Test Suite
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/introduction.md
Execute the entire test suite for a Dojo project.
```shell
dojo test
```
--------------------------------
### i18n Middleware Get
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Applications use this method to retrieve the currently set locale.
```typescript
i18n.get()
```
--------------------------------
### Mounting the Application
Source: https://github.com/dojo/framework/blob/master/docs/en/building/supplemental.md
Mount your application to the specified DOM node using the `renderer` and `mount` functions. This step is crucial for BTR to initialize the application within the designated HTML element.
```typescript
const r = renderer(() => w(App, {}));
const domNode = document.getElementById('app') as HTMLElement;
r.mount({ registry, domNode });
```
--------------------------------
### Theme Middleware Get
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Applications use this method to retrieve the currently set theme.
```typescript
theme.get(): Theme | undefined
```
--------------------------------
### Run Tests with BrowserStack via Command Line
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
Use this command to run tests on BrowserStack by providing your access key and username directly. Ensure you have signed up for a BrowserStack account.
```bash
dojo test -a -c browserstack -k --userName
```
--------------------------------
### includes
Source: https://github.com/dojo/framework/blob/master/docs/shim/string.md
Checks if a string contains a specified substring, optionally starting from a given position.
```APIDOC
## `includes`
### Description
Determines whether a string includes the given substring.
### Parameters
- **str** (string) - The string to search within.
- **searchString** (string) - The substring to search for.
- **position** (number, optional) - The index to begin searching at. Defaults to 0.
### Returns
(boolean) - `true` if the substring is found, `false` otherwise.
### Example
```ts
import { includes } from '@dojo/framework/shim/string';
const str = 'string';
const search = 'ring';
const position = 0;
const result = includes(str, search, position);
console.log(result); // Output: true
```
```
--------------------------------
### Form Widget Example
Source: https://github.com/dojo/framework/blob/master/docs/en/testing/supplemental.md
A widget that applies a 'focused' class when an input element receives focus.
```tsx
import { tsx, create } from '@dojo/framework/core/vdom';
import focus, { FocusProperties } from '@dojo/framework/core/middleware/focus';
import * as css from './FormWidget.m.css';
export interface FormWidgetProperties extends FocusProperties {}
const factory = create({ focus }).properties();
export const FormWidget = factory(function FormWidget({ middleware: { focus } }) {
return (
);
});
```
--------------------------------
### Create a Router Instance
Source: https://github.com/dojo/framework/blob/master/src/routing/README.md
Instantiate a Router with a route configuration. The router defaults to using HashHistory.
```typescript
const router = new Router(config);
```
--------------------------------
### Getting the current parameters
Source: https://github.com/dojo/framework/blob/master/docs/en/routing/supplemental.md
Shows how to access the parameters of the current route using the `currentParams` getter.
```APIDOC
## Getting the current parameters
```ts
import Router from '@dojo/framework/routing/Router';
import routes from './routes';
const router = new Router(routes);
// returns the current params for the route
const params = router.currentParams;
```
```
--------------------------------
### Retrieve a Value from a Map
Source: https://github.com/dojo/framework/blob/master/docs/shim/Map.md
Access the value associated with a specific key using the `get` method.
```typescript
import { Map } from '@dojo/framework/shim/Map';
var map = new Map([['age', 2], ['height', 1.5]]);
var key = 'age';
map.get(key) === 2; // true
```
--------------------------------
### Initialize Resource Template Options
Source: https://github.com/dojo/framework/blob/master/docs/en/resources/supplemental.md
Use the `init` function to process options passed to a template via the `resource` middleware. Options are defined using `createResourceTemplate`, where `INIT` specifies the required options.
```tsx
import { createResourceTemplate } from '@dojo/framework/core/middleware/resources';
// only showing the init api
const template = createResourceTemplate<{ foo: string }, { data: { foo: string; }[]; extra: number; }>({
init: (options, controls) => {
// the options matches the type passed as the second generic
const { data, extra } = options;
// use the controls to work with the store, for example store the init data
controls.put({ data, total: data.length});
}
});
interface ResourceInitRequest {
id: string;
data: S[];
}
export interface ResourceInit {
(request: I & { id: string; }, controls: ResourceControls): void;
}
```
--------------------------------
### Create Custom Breakpoint Middleware
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Example of creating a custom breakpoint middleware with predefined width breakpoints.
```typescript
import { createBreakpointMiddleware } from '@dojo/framework/core/middleware/breakpoint';
const myCustomBreakpoint = createBreakpointMiddleware({ Narrow: 0, Wide: 500 });
export default myCustomBreakpoint;
```
--------------------------------
### i18n Middleware Localize
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Widgets use this method to get localized message text for the current locale.
```typescript
i18n.localize(bundle: Bundle, useDefaults = false): LocalizedMessages
```
--------------------------------
### Creating a process
Source: https://github.com/dojo/framework/blob/master/docs/en/stores/introduction.md
A `Process` is used to sequentially execute commands against a `store`. Processes are created using the `createProcess` factory function.
```APIDOC
## Creating a process
### Description
First, create a couple commands responsible for obtaining a user token and use that token to load a `User`. Then create a process that uses those commands. Every process must be identified by a unique process ID. This ID is used internally in the store.
### Usage
```ts
import { createCommandFactory, createProcess } from "@dojo/framework/stores/process";
import { State } from './interfaces';
import { add, replace } from "@dojo/framework/stores/state/operations";
const createCommand = createCommandFactory();
const fetchUser = createCommand(async ({ at, get, payload: { username, password } }) => {
const token = await fetchToken(username, password);
return [
add(path('auth', 'token'), token);
];
}
const loadUserData = createCommand(async ({ path }) => {
const token = get(path('auth', 'token'));
const user = await fetchCurrentUser(token);
return [
replace(path('users', 'current'), user)
];
});
export const login = createProcess('login', [ fetchUser, loadUserData ]);
```
```
--------------------------------
### Theme Middleware Classes
Source: https://github.com/dojo/framework/blob/master/docs/en/middleware/supplemental.md
Widgets use this method to get theme-aware CSS class names for rendering.
```typescript
theme.classes(css: T): T
```
--------------------------------
### Get a matched route
Source: https://github.com/dojo/framework/blob/master/docs/en/routing/supplemental.md
Explains how to retrieve the `RouteContext` for a specific route ID using the `getRoute` method.
```APIDOC
## Get a matched route
Use the `getRoute` to return the `RouteContext` for a matched route id, or `undefined` if the route id's path is not matched.
`RouteContext`:
- `id: string`: The route id
- `outlet: string`: The outlet id
- `queryParams: { [index: string]: string }`: The query params from the matched routing.
- `params: { [index: string]: string }`: The path params from the matched routing.
- `isExact(): boolean`: A function indicates if the route is an exact match for the path.
- `isError(): boolean`: A function indicates if the route is an error match for the path.
- `type: 'index' | 'partial' | 'error'`: The type of match for the route, either `index`, `partial` or `error`.
```ts
import Router from '@dojo/framework/routing/Router';
import routes from './routes';
const router = new Router(routes);
// returns the route context if the `home` route is matched, otherwise `undefined`
const routeContext = router.getRoute('home');
```
```