Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/docs-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Documentation checks

on:
pull_request:
paths:
- 'README.md'
- 'context7.json'
- 'docs-tests/**'
- '.github/workflows/docs-check.yml'
push:
branches: [prod]
paths:
- 'README.md'
- 'context7.json'
- 'docs-tests/**'
- '.github/workflows/docs-check.yml'

permissions:
contents: read

jobs:
docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci --ignore-scripts --legacy-peer-deps
working-directory: docs-tests
- run: npm test
working-directory: docs-tests
11 changes: 11 additions & 0 deletions .github/workflows/pr-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,22 @@ jobs:
steps:
- uses: actions/checkout@v3

- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'npm'

- name: Record shell runtime
run: node --version && npm --version

- run: echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" > ~/.npmrc

- name: Install dependencies
run: npm ci --ignore-scripts

- name: Check build tooling
run: npm run test:build-tooling

- name: Check eslint
run: npm run lint:check

Expand Down
11 changes: 11 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,22 @@ jobs:
- name: Checkout
uses: actions/checkout@v3

- uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'npm'

- name: Record shell runtime
run: node --version && npm --version

- run: echo "//npm.pkg.github.com/:_authToken=${{ secrets.GITHUB_TOKEN }}" > ~/.npmrc

- name: Install dependencies
run: npm ci --ignore-scripts

- name: Check build tooling
run: npm run test:build-tooling

- name: Run check typescript
run: npm run ts:check

Expand Down
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
18.19.0
22.23.2
128 changes: 46 additions & 82 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,103 +27,67 @@ npm i --save @lomray/react-modals

## How to use

1. Add modal component types
```typescript
/**
* types/lomray/react-modals.d.ts
*/
import { IModalProps as IModalPropsDefault } from '@lomray/react-modals'
import { TDialogProps } from '@components/modals/default'

declare module '@lomray/react-modals' {
interface IModalProps extends IModalPropsDefault, TDialogProps {}
}
```
Use this to open application-owned modal content from hooks or refs. It supplies
lifecycle events and a root renderer, not styling, focus management, keyboard
handling, or an accessible dialog implementation. Supply those in your `Modal`
component. There is no `ModalProvider` export; `ModalRoot` is a named export.

2. Add ModalProvider and ModalRoot with Dialog (Modal) component
```typescript jsx
/**
* src/app.tsx
*/
import { ModalProvider } from '@lomray/react-modals';
import ModalRoot from '@lomray/react-modals';
import Layout from './components/layout';
import Dialog from './modals/default';

const App = () => (
<>
<Layout />
<ModalRoot Modal={(props) => <Dialog {...props} />} />
</>
)
```
Mount one `ModalRoot` per application and open modals after it has mounted. Roots
listen to shared event channels, so several roots are not independent scopes.
The small shell below demonstrates the wiring only, not a production dialog.

<!-- docs-test:example -->
```tsx
import React, { type FC, type PropsWithChildren } from 'react';
import { ModalRoot, useModal, type IModalToggle } from '@lomray/react-modals';

3. Create new modal layout with useModal hook
```typescript jsx
/**
* src/my-modal.tsx
*/
import type { IModalToggle } from '@lomray/react-modals';
import { createModalRef, useModal } from '@lomray/react-modals';
import React, { FC } from 'react';
const ModalShell: FC<PropsWithChildren<IModalToggle>> = ({ children, isVisible }) =>
isVisible ? <section>{children}</section> : null;

export interface IMyModal extends IModalToggle {
interface MessageProps extends IModalToggle {
text: string;
}

const MyModal: FC<IMyModal> = ({ closeModal, isVisible, text = 'default' }) => (
<div style={{ width: 300 }}>
<p>isVisible: {String(isVisible)}</p>
<p>text: {text}</p>
<button onClick={closeModal}>close</button>
const Message: FC<MessageProps> = ({ text, closeModal }) => (
<div>
<p>{text}</p>
<button onClick={closeModal}>Close</button>
</div>
);

export const myModalRef = createModalRef<IMyModal>();

const useMyModal = () =>
useModal(MyModal, {
className: 'additionalClassName',
hookRef: myModalRef,
});

export default useMyModal;
```

In cases where your modal window needs to access the parent store in Mobx, use the useModalMobx hook.

An example with Mobx can be found in Code examples
```typescript jsx
import { useModalMobx } from '@lomray/react-modals';
```


4. Use new modal in component via hook
```typescript jsx
/**
* src/layout.tsx
*/
import { FC } from 'react';
import useMyModal, { myModalRef } from './my-modal';

const Layout: FC = () => {
const [open] = useMyModal(); // [open, hide]

const OpenButton = () => {
const [open, hide] = useModal(Message);
return (
<div>
<button onClick={() => open({ text: 'open modal via hook' })}>
open modal via hook
</button>
<button onClick={() => myModalRef?.open({ text: 'open modal via ref' })}>
open modal via ref
</button>
</div>
<>
<button onClick={() => open({ text: 'Hello' })}>Open</button>
<button onClick={() => hide()}>Hide</button>
</>
);
};

export default Layout;
export const App = () => (
<>
<OpenButton />
<ModalRoot Modal={ModalShell} />
</>
);
```

`ModalRoot` unsubscribes when it unmounts. A modal opened by a hook does not
automatically close when that hook's owner unmounts; call `hide()` when your
application's lifecycle requires it. For access outside the owning component,
pass a `createModalRef<MessageProps>()` as `hookRef` in the second argument to
`useModal`; its methods are assigned by an effect, so do not call it before mount.

`useModalMobx` also passes the current MobX parent context ID to modal content.
It does not add a provider or style the dialog.

Release 2.0.1 declares peers on React, react-router-dom, @lomray/client-helpers and
@lomray/react-mobx-manager. Install compatible versions even for the basic hook;
the package root re-exports the MobX hook. The docs test records its pinned
fixture separately from these broad peer ranges. It checks opening and closing
in a simulated DOM, not accessibility or an SSR integration.

## Demo
Explore [demo app](https://github.com/Lomray-Software/modal-context-example) to more understand.

Expand Down
19 changes: 19 additions & 0 deletions context7.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"$schema": "https://context7.com/schema/context7.json",
"branch": "prod",
"folders": [],
"excludeFolders": [
"node_modules",
"lib",
"src",
"__tests__",
"__type_tests__",
"docs-tests",
".github"
],
"excludeFiles": [
"CHANGELOG.md",
"LICENSE.md",
"CODE_OF_CONDUCT.md"
]
}
2 changes: 2 additions & 0 deletions docs-tests/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
.generated/
17 changes: 17 additions & 0 deletions docs-tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Documentation checks

From this directory:

```sh
npm ci --ignore-scripts --legacy-peer-deps
npm test
```

The isolated fixture pins released dependencies, not local source. It validates
context7.json against the fetched official schema. For repositories with a marked
README example it extracts that block, runs a strict TypeScript check (skipping
external declaration checking), then runs a targeted smoke test. It is not the
full package suite, an exhaustive peer compatibility matrix, or an index refresh.
The registry lockfile records transitive versions. Peer auto-installation is
disabled so the tested combination stays explicit. Public network access is
needed for npm installation and the Context7 schema read.
76 changes: 76 additions & 0 deletions docs-tests/check.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import assert from 'node:assert/strict';
import { readFile, mkdir, writeFile, rm } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import { execFileSync } from 'node:child_process';
import { createRequire } from 'node:module';
import Ajv from 'ajv';

const root = new URL('../', import.meta.url);
const config = JSON.parse(await readFile(new URL('context7.json', root), 'utf8'));
const schemaResponse = await fetch('https://context7.com/schema/context7.json');
assert.equal(schemaResponse.status, 200);
const schema = await schemaResponse.json();
const ajv = new Ajv({ strict: false, formats: { uri: true } });
const validate = ajv.compile(schema);
assert.ok(validate(config), JSON.stringify(validate.errors));
assert.equal(config.branch, 'prod');
assert.ok(config.excludeFolders.includes('docs-tests'));
async function runExample(output) {
const { JSDOM } = await import('jsdom');
const dom = new JSDOM('<!doctype html><div id="root"></div>');
globalThis.window = dom.window;
globalThis.document = dom.window.document;
const navigatorDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'navigator');
Object.defineProperty(globalThis, 'navigator', { value: dom.window.navigator, configurable: true });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
const React = await import('react');
const { createRoot } = await import('react-dom/client');
const { App } = await import(output.href);
const root = createRoot(document.getElementById('root'));
const click = async (text) => {
const button = [...document.querySelectorAll('button')].find((el) => el.textContent === text);
assert.ok(button, `Missing button: ${text}`);
await React.act(async () => button.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true })));
};
try {
await React.act(async () => root.render(React.createElement(App)));
await click('Open');
assert.equal(document.querySelector('section p')?.textContent, 'Hello');
await click('Close');
assert.equal(document.querySelector('section'), null);
await click('Open');
await click('Hide');
assert.equal(document.querySelector('section'), null);
} finally {
await React.act(async () => root.unmount());
dom.window.close();
delete globalThis.window;
delete globalThis.document;
if (navigatorDescriptor) {
Object.defineProperty(globalThis, 'navigator', navigatorDescriptor);
} else {
delete globalThis.navigator;
}
delete globalThis.IS_REACT_ACT_ENVIRONMENT;
}
}

const require = createRequire(import.meta.url);
const { build } = await import('esbuild');
const dir = new URL('.generated/', import.meta.url);
await mkdir(dir, { recursive: true });
try {
const readme = await readFile(new URL('README.md', root), 'utf8');
const matches = [...readme.matchAll(/<!-- docs-test:example -->\s*```(?:typescript|tsx)\n([\s\S]*?)```/g)];
assert.equal(matches.length, 1, 'Expected exactly one marked README example');
const input = new URL('example.tsx', dir);
await writeFile(input, matches[0][1]);
const tsc = require.resolve('typescript/bin/tsc');
execFileSync(process.execPath, [tsc, '--noEmit', '--strict', '--skipLibCheck', '--target', 'ES2022', '--module', 'ESNext', '--moduleResolution', 'bundler', '--jsx', 'react-jsx', '--esModuleInterop', fileURLToPath(input)], { stdio: 'inherit' });
const output = new URL('example.mjs', dir);
await build({ entryPoints: [fileURLToPath(input)], outfile: fileURLToPath(output), bundle: true, platform: 'node', format: 'esm', packages: 'external', jsx: 'automatic', logLevel: 'silent' });
await runExample(output);
console.log('PASS: Context7 schema, README semantic typecheck and released-package smoke');
} finally {
await rm(dir, { recursive: true, force: true });
}
Loading
Loading