feat: initialize project structure with core components and pages
CI / Lint, typecheck, test, build (push) Canceled after 0s
CI / End-to-end tests (push) Canceled after 0s

- Added shared styles for UI components in `src/components/styles.ts`.
- Created configuration constants in `src/lib/config.ts`.
- Implemented date formatting and greeting functions in `src/lib/dates.ts` and corresponding tests in `src/lib/dates.test.ts`.
- Developed incident management functions in `src/lib/incidents.ts` with tests in `src/lib/incidents.test.ts`.
- Established navigation structure in `src/lib/navigation.ts`.
- Seeded demo data for incidents and users in `src/lib/seed.ts`.
- Defined tone classes for UI elements in `src/lib/tones.ts`.
- Created type definitions for incidents and related entities in `src/lib/types.ts`.
- Set up main application entry point in `src/main.tsx`.
- Developed various pages including About, Analytics, Incidents, Locations, Overview, and Report Incident.
- Configured testing setup in `src/test/setup.ts` and TypeScript configurations.
- Integrated Vite for development and testing with appropriate plugins.
This commit is contained in:
jayjennings committed 2026-10-06 10:07:57 -07:00
1 parent 732d4d8931
commit a382fa904a
53 files changed
+3523 -31

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
name: CI
on:
push:
branches: [main]
pull_request:
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
name: Lint, typecheck, test, build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run lint
- run: npm run typecheck
- run: npm test
- run: npm run build
e2e:
name: End-to-end tests
runs-on: ubuntu-latest
# Keep this tag in sync with the @playwright/test version in package-lock.json
container: mcr.microsoft.com/playwright:v1.63.0-noble
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npm run test:e2e
env:
HOME: /root
- uses: actions/upload-artifact@v3
if: failure()
with:
name: playwright-report
path: playwright-report
retention-days: 7
+9
View File
@@ -22,3 +22,12 @@ dist-ssr
*.njsproj
*.sln
*.sw?
# TypeScript
*.tsbuildinfo
# Tests
coverage
test-results
playwright-report
blob-report
+1
View File
@@ -0,0 +1 @@
24
+5 -3
View File
@@ -1,8 +1,10 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "oxc"],
"plugins": ["react", "typescript", "oxc", "jsx-a11y", "vitest"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
"react/only-export-components": ["warn", { "allowConstantExport": true }],
"jsx-a11y/control-has-associated-label": "off"
},
"ignorePatterns": ["dist", "playwright-report", "test-results"]
}
+83
View File
@@ -0,0 +1,83 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [CONTACT EMAIL TO BE ADDED — see docs/TODO.md]. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of actions.
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+50
View File
@@ -0,0 +1,50 @@
# Contributing to Open SafetyLog EHS
Thanks for helping make workplace safety software free for everyone. Contributions of all kinds are welcome: bug reports, feature ideas, documentation, design, translations and code.
Everyone taking part is expected to follow our [Code of Conduct](CODE_OF_CONDUCT.md).
## Ways to contribute
- **Report a bug.** Open an issue with steps to reproduce, what you expected, what happened, and your browser and device.
- **Suggest a feature.** Open an issue describing the safety problem you're trying to solve, not only the solution. Real-world context from plants and safety teams is especially valuable.
- **Pick up work.** Check the [roadmap](docs/ROADMAP.md) and [to-do list](docs/TODO.md). Comment on an issue before starting anything large so we can agree on the approach.
## Development setup
Requires Node.js 22.12 or later (see `.nvmrc`).
```sh
npm install
npx playwright install chromium # once, for end-to-end tests
npm run dev
```
Before opening a pull request, run:
```sh
npm run check # lint, typecheck, unit tests, build
npm run test:e2e # end-to-end tests on desktop and mobile
```
CI runs the same checks on every pull request.
## Code guidelines
- **TypeScript** everywhere; avoid `any`.
- **Structure:** routes go in `src/pages/`, reusable UI in `src/components/`, and types and domain logic in `src/lib/` (no React components there).
- **Styling:** Tailwind CSS. Use the theme tokens in `src/index.css` (`text-ink`, `bg-coral`, `border-line`, …) rather than new hex values; add a token if a color is reused.
- **Tests:** put domain logic in `src/lib/` with a unit test next to it (`*.test.ts`). Cover user-facing flows with a component test or a Playwright test in `e2e/`.
- **Accessibility:** every form control needs a label, and every icon-only button needs an `aria-label`. Shop-floor users may be on gloves-on touchscreens, so keep touch targets generous.
- **Safety data:** incident and injury records can contain medical and personal information. Never log them, and never add third-party scripts, fonts or analytics that would send data off the server.
## Commits and pull requests
- Branch from `main` and keep each pull request focused on one change.
- Use [Conventional Commits](https://www.conventionalcommits.org/) messages, e.g. `feat: add QR code location labels` or `fix: keep filter when returning to list`.
- Describe what changed and why, link related issues, and add screenshots for UI changes (desktop and mobile).
- Update `docs/ROADMAP.md` or `docs/TODO.md` if your change completes or adds an item.
## License
Open SafetyLog EHS is licensed under the [GNU Affero General Public License v3.0](LICENSE). By submitting a contribution, you agree that it is licensed under the same terms.
+235
View File
@@ -0,0 +1,235 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based on the Program.
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
+43 -9
View File
@@ -1,16 +1,50 @@
# React + Vite
# Open SafetyLog EHS
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Free, open-source accident and safety tracking for manufacturing: incident and near-miss reporting, investigations, corrective actions and (planned) OSHA record keeping.
Currently, two official plugins are available:
> **Status: early prototype.** The UI runs on in-memory demo data; nothing is saved yet. See [docs/ROADMAP.md](docs/ROADMAP.md) for the plan and [docs/TODO.md](docs/TODO.md) for open items.
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## Getting started
## React Compiler
Requires Node.js 22.12 or later (see `.nvmrc`).
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
```sh
npm install
npm run dev
```
## Expanding the Oxlint configuration
## Scripts
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and Oxlint's TypeScript related rules in your project.
| Command | What it does |
| --- | --- |
| `npm run dev` | Start the dev server |
| `npm run build` | Production build to `dist/` |
| `npm run lint` | Lint with Oxlint (warnings fail) |
| `npm run typecheck` | Type-check with TypeScript |
| `npm test` | Unit and component tests (Vitest) |
| `npm run test:e2e` | End-to-end tests (Playwright, desktop and mobile). Run `npx playwright install chromium` once first |
| `npm run check` | Lint, typecheck, test and build in one go |
CI runs the same checks on every push and pull request (`.gitea/workflows/ci.yml`).
## Project layout
```
src/
pages/ One component per route
components/ Shared UI (layout, tables, form pieces) and shared class strings in styles.ts
lib/ Types, domain logic, demo data; no React components
index.css Tailwind import and design tokens (@theme)
e2e/ Playwright tests
docs/ Roadmap and design notes
```
Styling is Tailwind CSS v4. Colors, fonts and small text sizes are defined as theme tokens in `src/index.css`. Fonts are bundled through Fontsource, so the app makes no third-party requests and works on isolated plant networks.
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md). Everyone taking part follows our [Code of Conduct](CODE_OF_CONDUCT.md).
## License
[GNU Affero General Public License v3.0](LICENSE). If you run a modified version as a network service, you must offer its source code to its users. The app's About page links to the source; set `VITE_SOURCE_URL` at build time to point it at your fork.
+82
View File
@@ -0,0 +1,82 @@
# Open SafetyLog EHS Roadmap
A free, open-source (AGPL-3.0) accident and safety tracking system for manufacturing.
This is a living document. Update it as decisions are made or scope changes.
## Decisions
| Topic | Decision | Status |
| --- | --- | --- |
| License | AGPL-3.0-only | Decided |
| Frontend | React + Vite + TypeScript, Tailwind CSS v4 | Decided |
| Backend | Node (Fastify or Hono) + PostgreSQL + Drizzle ORM, shared Zod schemas | Proposed |
| Deployment | Self-hosted, single `docker compose up` (app + Postgres + file storage) | Proposed |
| Compliance scope | US OSHA first; data model kept extensible for other regions (e.g. RIDDOR) | Proposed |
| CI | Gitea Actions (`.gitea/workflows`): lint, typecheck, unit tests, build, e2e | Decided |
| Product name | Open SafetyLog EHS (replaced placeholder "IA Tracker" and the prototype's "Safesite" branding) | Decided |
## Phase 0: Foundation
- [x] AGPL-3.0 LICENSE
- [x] Convert to TypeScript
- [x] Split `App.jsx` into `pages/`, `components/`, `lib/`
- [x] Convert styling to Tailwind (remove hand-written `App.css`)
- [x] Remove unused template files
- [x] Bundle fonts locally (no Google Fonts dependency for offline/locked-down plant networks)
- [x] CI: lint, typecheck, unit tests (Vitest), build, e2e (Playwright)
- [x] Replace template README
- [x] CONTRIBUTING.md and CODE_OF_CONDUCT.md
- [x] About page with source-code link (AGPL section 13)
- [ ] Remaining setup items (name, CoC contact, final source URL, CI runner): see [TODO.md](TODO.md)
## Phase 1: Backend and data model
- Entities: Organization, Site → Area (location tree), User, Role, Incident (type, severity, status, timestamps, reporter or anonymous), InjuredPerson and injury details, Attachment, Investigation, RootCause, CorrectiveAction, Comment, AuditLog, HoursWorked
- Auth: email/password and magic links; SSO/OIDC later; role-based permissions
- REST API with pagination, filtering and sequential incident numbering
## Phase 2: Core workflow (MVP)
- Reporting that saves to the database, with photo upload
- Incident detail page: timeline, investigation, root-cause tools (5 Whys, fishbone), corrective actions (CAPA)
- Status workflow: Reported → Triage → Investigation → Corrective actions → Verification → Closed, with role-based transitions
- "My actions" list and overdue tracking
- Email notifications: assignment, due dates, high-severity alerts
- CSV and PDF export
- Dashboard metrics computed from real data
## Phase 3: Shop-floor reporting
- Installable PWA with offline queue (sync when connection returns)
- Printable QR codes per area that pre-fill the location
- Kiosk mode and anonymous reporting
- Multi-language support, Spanish first
## Phase 4: Compliance (US OSHA)
- Recordability wizard; days away / restricted / transferred tracking
- OSHA 300, 300A and 301 form generation; privacy-case handling
- ITA (Injury Tracking Application) CSV export
- Hours worked per site per month; TRIR, DART and lost-time rates
## Phase 5: Analytics
- Trends, location breakdown, top root causes, corrective-action closure time
- Leading vs lagging indicators; filters and saved dashboards
## Phase 6: Release v1.0
- Docker images, backup and restore
- Demo instance with seed data
- Documentation site and upgrade guide
## Later
Inspections and audit checklists, job safety analysis (JSA), training and certification records, management of change, SDS links, public API and webhooks.
## Known prototype gaps (to be resolved in Phases 1–2)
- All data is in memory and resets on refresh
- Dashboard, analytics and location figures are hardcoded
- Export, Add location, Settings, Resources, search, notifications and workspace switcher are non-functional
+15
View File
@@ -0,0 +1,15 @@
# To-do
Open items that aren't tied to a single roadmap phase. Tick them off (or delete them) as they're resolved. Phase work lives in [ROADMAP.md](ROADMAP.md).
## Project setup
- [ ] **Code of Conduct contact.** Replace the placeholder in [CODE_OF_CONDUCT.md](../CODE_OF_CONDUCT.md) with a reporting email address, ideally a project alias rather than a personal one.
- [ ] **Source code link.** The About page links to `https://www.equineform.com` for now (default in `src/lib/config.ts`, overridable with `VITE_SOURCE_URL`). Change it to the public git repository once one exists, and use the same URL for issue links in CONTRIBUTING.md.
- [ ] **CI on Gitea.** Confirm Actions is enabled for the repository and a runner is registered, then check the first run of `.gitea/workflows/ci.yml` passes. Keep the Playwright container tag in the workflow in sync with `@playwright/test`.
## Done
- [x] Product name: **Open SafetyLog EHS** (decided 2026-10-06). Note: Insight Works sells a similarly named free "Safety Logbook" EHS app for Microsoft Business Central; run a USPTO trademark search before a public launch.
- [x] CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1)
- [x] About page with source-code link (AGPL-3.0 section 13)
+33
View File
@@ -0,0 +1,33 @@
import { expect, test } from '@playwright/test'
test('navigates between the main pages', async ({ page, isMobile }) => {
await page.goto('/')
await expect(page.getByRole('heading', { level: 1 })).toContainText('Jordan')
for (const name of ['Incidents', 'Locations', 'Analytics']) {
if (isMobile) await page.getByRole('button', { name: 'Open menu' }).click()
await page.getByRole('navigation').getByRole('link', { name }).click()
await expect(page.getByRole('heading', { level: 1, name })).toBeVisible()
}
})
test('reports an incident', async ({ page }) => {
await page.goto('/report')
await page.getByLabel('Incident title').fill('Blocked fire exit in warehouse')
await page.getByLabel('Specific location').fill('North exit')
await page.getByRole('button', { name: /submit report/i }).click()
await expect(page).toHaveURL(/\/incidents$/)
await expect(page.getByText('Blocked fire exit in warehouse')).toBeVisible()
})
test('loads bundled fonts without third-party requests', async ({ page }) => {
const external: string[] = []
page.on('request', (request) => {
if (!request.url().startsWith('http://localhost')) external.push(request.url())
})
await page.goto('/')
await page.evaluate(() => document.fonts.ready)
expect(await page.evaluate(() => document.fonts.check('16px "DM Sans Variable"'))).toBe(true)
expect(external).toEqual([])
})
+3 -2
View File
@@ -4,10 +4,11 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>iatracker</title>
<title>Open SafetyLog EHS</title>
<meta name="description" content="Open-source accident and safety tracking for manufacturing" />
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+1558 -5
View File
File diff suppressed because it is too large. Load diff
+26 -5
View File
@@ -1,15 +1,28 @@
{
"name": "iatracker",
"name": "open-safetylog-ehs",
"version": "0.1.0",
"description": "Open-source accident and safety tracking for manufacturing",
"license": "AGPL-3.0-only",
"private": true,
"version": "0.0.0",
"type": "module",
"engines": {
"node": ">=22.12"
},
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "oxlint",
"preview": "vite preview"
"preview": "vite preview",
"lint": "oxlint --deny-warnings",
"typecheck": "tsc -b",
"test": "vitest run",
"test:watch": "vitest",
"test:e2e": "playwright test",
"check": "npm run lint && npm run typecheck && npm test && npm run build"
},
"dependencies": {
"@fontsource-variable/dm-sans": "^5.3.0",
"@fontsource-variable/space-grotesk": "^5.3.0",
"@fontsource/dm-mono": "^5.3.0",
"@tailwindcss/vite": "^4.3.3",
"lucide-react": "^1.39.0",
"react": "^19.2.8",
@@ -18,10 +31,18 @@
"tailwindcss": "^4.3.3"
},
"devDependencies": {
"@playwright/test": "^1.63.0",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.7",
"@types/node": "^26.6.4",
"@types/react": "^19.2.18",
"@types/react-dom": "^19.2.4",
"@vitejs/plugin-react": "^6.1.0",
"jsdom": "^30.1.2",
"oxlint": "^1.79.0",
"vite": "^8.2.2"
"typescript": "^7.0.2",
"vite": "^8.2.2",
"vitest": "^5.0.3"
}
}
+24
View File
@@ -0,0 +1,24 @@
import { defineConfig, devices } from '@playwright/test'
const port = 4173
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
reporter: process.env.CI ? [['list'], ['html', { open: 'never' }]] : 'list',
use: {
baseURL: `http://localhost:${port}`,
trace: 'on-first-retry',
},
projects: [
{ name: 'desktop', use: { ...devices['Desktop Chrome'] } },
{ name: 'mobile', use: { ...devices['Pixel 7'] } },
],
webServer: {
command: `npm run build && npm run preview -- --port ${port} --strictPort`,
port,
reuseExistingServer: !process.env.CI,
},
})
+1 -1
View File
@@ -1 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#ee7258"/><path d="M16 6.5 8.5 9.5v6c0 4.6 3.2 8.6 7.5 9.9 4.3-1.3 7.5-5.3 7.5-9.9v-6L16 6.5Z" fill="none" stroke="#fff" stroke-width="2.2" stroke-linejoin="round"/><path d="m12.5 16 2.4 2.4 4.6-4.8" fill="none" stroke="#fff" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>

Before

Width:  |  Height:  |  Size: 9.3 KiB

After

Width:  |  Height:  |  Size: 402 B

+51
View File
@@ -0,0 +1,51 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it } from 'vitest'
import App from './App'
function renderAt(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
)
}
describe('App', () => {
it('renders the overview with recent incidents', () => {
renderAt('/')
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent(/Jordan/)
expect(screen.getByText('Forklift reversed into pallet stack')).toBeInTheDocument()
})
it('adds a submitted report to the incident register', async () => {
const user = userEvent.setup()
renderAt('/report')
await user.type(screen.getByLabelText('Incident title'), 'Oil leak under press 4')
await user.selectOptions(screen.getByLabelText('Incident type'), 'Hazard')
await user.type(screen.getByLabelText('Specific location'), 'Press line')
await user.click(screen.getByRole('button', { name: /submit report/i }))
expect(screen.getByRole('heading', { level: 1, name: 'Incidents' })).toBeInTheDocument()
expect(screen.getByText('Oil leak under press 4')).toBeInTheDocument()
expect(screen.getByText(/INC-2409/)).toBeInTheDocument()
})
it('filters the incident register by search text', async () => {
const user = userEvent.setup()
renderAt('/incidents')
await user.type(screen.getByLabelText('Search incidents'), 'guardrail')
expect(screen.getByText('Damaged guardrail on mezzanine')).toBeInTheDocument()
expect(screen.queryByText('Forklift reversed into pallet stack')).not.toBeInTheDocument()
})
it('links to the source code from the about page', () => {
renderAt('/about')
expect(screen.getByRole('heading', { level: 1, name: 'About Open SafetyLog EHS' })).toBeInTheDocument()
expect(screen.getByRole('link', { name: /view source code/i })).toHaveAttribute('href', 'https://www.equineform.com')
})
})
+33
View File
@@ -0,0 +1,33 @@
import { useState } from 'react'
import { Navigate, Route, Routes } from 'react-router-dom'
import { AppLayout } from './components/AppLayout'
import { createIncident, isOpen } from './lib/incidents'
import { currentUser, seedIncidents } from './lib/seed'
import type { NewIncident } from './lib/types'
import { About } from './pages/About'
import { Analytics } from './pages/Analytics'
import { Incidents } from './pages/Incidents'
import { Locations } from './pages/Locations'
import { Overview } from './pages/Overview'
import { ReportIncident } from './pages/ReportIncident'
export default function App() {
// In-memory store until the backend lands (Phase 1)
const [incidents, setIncidents] = useState(seedIncidents)
const addIncident = (report: NewIncident) =>
setIncidents((current) => [createIncident(report, current, currentUser.name, new Date()), ...current])
return (
<Routes>
<Route element={<AppLayout openIncidentCount={incidents.filter(isOpen).length} />}>
<Route index element={<Overview incidents={incidents} />} />
<Route path="incidents" element={<Incidents incidents={incidents} />} />
<Route path="locations" element={<Locations />} />
<Route path="analytics" element={<Analytics />} />
<Route path="report" element={<ReportIncident onSubmit={addIncident} />} />
<Route path="about" element={<About />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Route>
</Routes>
)
}
+17
View File
@@ -0,0 +1,17 @@
import { useState } from 'react'
import { Outlet } from 'react-router-dom'
import { Header } from './Header'
import { Sidebar } from './Sidebar'
export function AppLayout({ openIncidentCount }: { openIncidentCount: number }) {
const [menuOpen, setMenuOpen] = useState(false)
return (
<div className="flex min-h-screen bg-canvas">
<Sidebar open={menuOpen} onClose={() => setMenuOpen(false)} openIncidentCount={openIncidentCount} />
<main className="min-w-0 flex-1">
<Header onOpenMenu={() => setMenuOpen(true)} />
<Outlet />
</main>
</div>
)
}
+5
View File
@@ -0,0 +1,5 @@
import type { ReactNode } from 'react'
export function Eyebrow({ children, className = 'text-[#8da29b]' }: { children: ReactNode; className?: string }) {
return <span className={`block font-mono text-3xs font-medium tracking-[0.09em] uppercase ${className}`}>{children}</span>
}
+33
View File
@@ -0,0 +1,33 @@
import type { ReactNode } from 'react'
interface FormSectionProps {
number: string
title: string
copy: string
children: ReactNode
}
export function FormSection({ number, title, copy, children }: FormSectionProps) {
return (
<div className="border-b border-line px-5 py-6 sm:px-9 sm:py-7">
<div className="mb-6 flex gap-[13px]">
<span className="pt-[3px] font-mono text-xs text-coral">{number}</span>
<div>
<h2 className="mb-1 font-display text-[19px] font-semibold">{title}</h2>
<p className="text-xs text-muted">{copy}</p>
</div>
</div>
{children}
</div>
)
}
export function Field({ label, optional = false, children }: { label: string; optional?: boolean; children: ReactNode }) {
return (
<label className="mb-[17px] block text-2xs font-semibold text-[#586762]">
{label}
{optional && <em className="float-right font-normal text-[#9ba7a2] not-italic">Optional</em>}
{children}
</label>
)
}
+31
View File
@@ -0,0 +1,31 @@
import { Bell, Menu, Search } from 'lucide-react'
import { useLocation } from 'react-router-dom'
import { pageTitles } from '../lib/navigation'
import { currentUser } from '../lib/seed'
import { iconButton } from './styles'
export function Header({ onOpenMenu }: { onOpenMenu: () => void }) {
const { pathname } = useLocation()
return (
<header className="flex h-[62px] items-center justify-between border-b border-line bg-white/60 px-[17px] sm:h-[72px] sm:px-6 lg:px-[42px]">
<button type="button" className={`${iconButton} mr-2.5 sm:hidden`} onClick={onOpenMenu} aria-label="Open menu">
<Menu size={21} />
</button>
<div className="flex items-center gap-2.5 text-xs text-[#94a09b]">
<span className="max-sm:hidden">Safety workspace</span>
<span className="max-sm:hidden">/</span>
<strong className="text-ink">{pageTitles[pathname] ?? 'Not found'}</strong>
</div>
<div className="flex items-center gap-[15px]">
<button type="button" className={iconButton} aria-label="Search">
<Search size={19} />
</button>
<button type="button" className={`${iconButton} relative`} aria-label="Notifications">
<Bell size={19} />
<i className="absolute top-1 right-[3px] size-1.5 rounded-full border border-canvas bg-coral" />
</button>
<div className="grid size-8 place-items-center rounded-full bg-[#d2e0d8] font-mono text-2xs text-teal">{currentUser.initials}</div>
</div>
</header>
)
}
+80
View File
@@ -0,0 +1,80 @@
import { AlertTriangle, MapPin } from 'lucide-react'
import { formatDate } from '../lib/dates'
import { severityDotClass, statusClass, typeTone } from '../lib/incidents'
import { toneClasses } from '../lib/tones'
import type { Incident } from '../lib/types'
import { iconButton } from './styles'
const th = 'border-b border-line px-2.5 py-3 font-mono text-3xs font-medium tracking-[0.06em] text-faint uppercase first:pl-6 last:pr-[18px]'
const td = 'border-b border-line-soft px-2.5 py-3.5 text-2xs whitespace-nowrap text-body first:pl-6 last:pr-[18px]'
interface IncidentTableProps {
incidents: Incident[]
limit?: number
wide?: boolean
}
export function IncidentTable({ incidents, limit, wide = false }: IncidentTableProps) {
const rows = limit ? incidents.slice(0, limit) : incidents
return (
<div className="overflow-auto">
<table className={`w-full border-collapse text-left ${wide ? 'min-w-[900px]' : 'min-w-[720px]'}`}>
<thead>
<tr>
<th className={th}>Incident</th>
<th className={th}>Type</th>
<th className={th}>Severity</th>
<th className={th}>Location</th>
<th className={th}>Status</th>
<th className={th}>Date</th>
<th className={th}>
<span className="sr-only">Actions</span>
</th>
</tr>
</thead>
<tbody>
{rows.map((incident) => (
<tr key={incident.id} className="[&:last-child>td]:border-b-0">
<td className={td}>
<div className="flex min-w-[250px] items-center gap-2.5">
<span className={`grid size-7 place-items-center rounded-[7px] ${toneClasses[typeTone[incident.type]]}`}>
<AlertTriangle size={14} />
</span>
<div>
<strong className="block text-xs font-semibold text-ink">{incident.title}</strong>
<small className="mt-1 block text-3xs text-faint">
{incident.id} · {incident.reporter}
</small>
</div>
</div>
</td>
<td className={td}>{incident.type}</td>
<td className={td}>
<span className="inline-flex items-center gap-[5px]">
<i className={`size-1.5 rounded-full ${severityDotClass[incident.severity]}`} />
{incident.severity}
</span>
</td>
<td className={td}>
<div className="flex max-w-[120px] flex-wrap items-center gap-1">
<MapPin size={14} />
{incident.location}
<small className="mt-1 ml-[18px] block w-full text-3xs text-faint">{incident.building}</small>
</div>
</td>
<td className={td}>
<span className={`rounded px-2 py-[5px] text-3xs ${statusClass(incident.status)}`}>{incident.status}</span>
</td>
<td className={`${td} text-[#87938f]`}>{formatDate(incident.date)}</td>
<td className={td}>
<button type="button" className={iconButton} aria-label={`More actions for ${incident.id}`}>
<span className="tracking-[2px] text-[#91aaa0]">•••</span>
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
import type { LucideIcon } from 'lucide-react'
import { toneClasses, type Tone } from '../lib/tones'
interface MetricCardProps {
label: string
value: string
delta: string
icon: LucideIcon
tone: Tone
}
export function MetricCard({ label, value, delta, icon: Icon, tone }: MetricCardProps) {
return (
<div className="rounded-lg border border-line bg-white p-[13px] sm:p-[18px]">
<div className={`grid size-[35px] place-items-center rounded-[7px] ${toneClasses[tone]}`}>
<Icon size={19} />
</div>
<span className="mt-2.5 mb-1.5 block text-xs text-muted sm:mt-[15px]">{label}</span>
<strong className="block font-display text-[25px] font-semibold tracking-[-1px] text-ink sm:text-[30px]">{value}</strong>
<small className="mt-[9px] block text-[9px] text-[#7d8b86] sm:text-2xs">
<b className="text-positive">↗</b> {delta}
</small>
</div>
)
}
+9
View File
@@ -0,0 +1,9 @@
import type { ReactNode } from 'react'
export function Page({ children, narrow = false }: { children: ReactNode; narrow?: boolean }) {
return (
<div className={`mx-auto px-[17px] pt-7 pb-10 sm:px-6 sm:pt-10 sm:pb-[60px] lg:px-[42px] ${narrow ? 'max-w-[900px]' : 'max-w-[1360px]'}`}>
{children}
</div>
)
}
+22
View File
@@ -0,0 +1,22 @@
import type { ReactNode } from 'react'
import { Eyebrow } from './Eyebrow'
interface PageIntroProps {
eyebrow: string
title: string
copy?: string
action?: ReactNode
}
export function PageIntro({ eyebrow, title, copy, action }: PageIntroProps) {
return (
<div className="mb-[31px] flex flex-col items-start gap-5 sm:flex-row sm:items-center sm:justify-between">
<div>
<Eyebrow>{eyebrow}</Eyebrow>
<h1 className="mt-[7px] mb-[5px] font-display text-[29px] font-semibold tracking-[-1px] text-ink sm:text-[34px]">{title}</h1>
{copy && <p className="text-sm text-muted">{copy}</p>}
</div>
{action}
</div>
)
}
+25
View File
@@ -0,0 +1,25 @@
import { ArrowUpRight } from 'lucide-react'
import { NavLink } from 'react-router-dom'
import { Eyebrow } from './Eyebrow'
interface PanelHeadingProps {
eyebrow: string
title: string
link?: { label: string; to: string }
}
export function PanelHeading({ eyebrow, title, link }: PanelHeadingProps) {
return (
<div className="flex items-center justify-between px-[17px] pt-[19px] pb-3.5 sm:px-6 sm:pt-6 sm:pb-[18px]">
<div>
<Eyebrow>{eyebrow}</Eyebrow>
<h2 className="mt-1.5 font-display text-[19px] font-semibold text-ink">{title}</h2>
</div>
{link && (
<NavLink to={link.to} className="inline-flex items-center gap-[5px] text-xs font-bold text-coral">
{link.label} <ArrowUpRight size={15} />
</NavLink>
)}
</div>
)
}
+34
View File
@@ -0,0 +1,34 @@
interface ProgressBarProps {
/** 0–100 */
percent: number
barClassName?: string
className?: string
}
export function ProgressBar({ percent, barClassName = 'bg-coral', className = '' }: ProgressBarProps) {
return (
<div className={`mt-2 h-1.5 overflow-hidden rounded-full bg-[#edf1ed] ${className}`}>
<i className={`block h-full rounded-full ${barClassName}`} style={{ width: `${percent}%` }} />
</div>
)
}
interface ProgressRowProps {
label: string
value: string
percent: number
variant?: 'action' | 'location'
}
export function ProgressRow({ label, value, percent, variant = 'action' }: ProgressRowProps) {
const isLocation = variant === 'location'
return (
<div className={isLocation ? 'px-6 py-[7px]' : 'px-6 pt-3'}>
<div className={`flex justify-between text-2xs ${isLocation ? 'text-[#63726d]' : 'text-muted'}`}>
<span>{label}</span>
<strong className="font-mono font-normal text-ink">{value}</strong>
</div>
<ProgressBar percent={percent} barClassName={isLocation ? 'bg-sage' : 'bg-coral'} />
</div>
)
}
+89
View File
@@ -0,0 +1,89 @@
import { ChevronDown, FileText, Info, Plus, Settings, ShieldCheck, X } from 'lucide-react'
import { NavLink } from 'react-router-dom'
import { primaryNav } from '../lib/navigation'
import { currentUser, workspace } from '../lib/seed'
import { Eyebrow } from './Eyebrow'
import { iconButton } from './styles'
const navLink = ({ isActive }: { isActive: boolean }) =>
`flex h-[42px] items-center gap-3 rounded-md px-3 text-[13px] hover:bg-forest-800 hover:text-white ${isActive ? 'bg-forest-800 text-white' : 'text-forest-200'}`
const navSection = 'mb-6 border-b border-forest-700 pb-[23px]'
interface SidebarProps {
open: boolean
onClose: () => void
openIncidentCount: number
}
export function Sidebar({ open, onClose, openIncidentCount }: SidebarProps) {
return (
<aside
className={`fixed inset-y-0 z-10 flex w-[260px] flex-none flex-col overflow-y-auto bg-forest-950 px-[15px] pt-7 pb-[18px] text-forest-100 shadow-[8px_0_30px_#163c3740] transition-[left] duration-200 sm:static sm:min-h-screen sm:w-[230px] sm:shadow-none lg:w-[246px] ${open ? 'left-0' : '-left-[270px]'}`}
>
<div className="flex items-center gap-2.5 px-3 pb-[31px] text-white">
<div className="grid size-[34px] flex-none place-items-center rounded-[9px] bg-coral text-white">
<ShieldCheck size={20} />
</div>
<div>
<strong className="block font-display text-[19px] leading-tight sm:text-[17px] lg:text-[19px] font-bold tracking-[-0.5px] whitespace-nowrap">Open SafetyLog</strong>
<span className="mt-0.5 block text-3xs text-forest-300">EHS · Incident intelligence</span>
</div>
<button type="button" className={`${iconButton} absolute top-2 right-2 sm:hidden`} onClick={onClose} aria-label="Close menu">
<X size={20} />
</button>
</div>
<div className="mb-[27px] flex items-center gap-2.5 rounded-[7px] border border-[#316158] p-[11px]">
<div className="grid size-[29px] place-items-center rounded-full bg-[#f1c865] font-mono text-2xs font-bold text-[#143d37]">{workspace.initials}</div>
<div>
<Eyebrow>Workspace</Eyebrow>
<strong className="block text-[13px] text-white">{workspace.name}</strong>
</div>
<ChevronDown size={16} className="ml-auto" />
</div>
<nav className={navSection}>
{primaryNav.map(({ label, to, icon: Icon }) => (
<NavLink key={to} to={to} end onClick={onClose} className={navLink}>
<Icon size={18} />
<span>{label}</span>
{to === '/incidents' && openIncidentCount > 0 && (
<em className="ml-auto rounded-[10px] bg-coral px-[7px] py-0.5 font-mono text-2xs text-white not-italic">{openIncidentCount}</em>
)}
</NavLink>
))}
</nav>
<div className={navSection}>
<Eyebrow className="px-3 pb-2 text-[#8da29b]">Manage</Eyebrow>
<NavLink to="/report" onClick={onClose} className={navLink}>
<Plus size={18} />
<span>Report an incident</span>
</NavLink>
<a href="#resources" className={navLink({ isActive: false })}>
<FileText size={18} />
<span>Resources</span>
</a>
</div>
<div className="mt-auto">
<NavLink to="/about" onClick={onClose} className={navLink}>
<Info size={18} />
<span>About</span>
</NavLink>
<a href="#settings" className={navLink({ isActive: false })}>
<Settings size={18} />
<span>Settings</span>
</a>
<div className="mt-4 flex items-center gap-2.5 border-t border-forest-700 px-2 pt-5">
<div className="grid size-[31px] place-items-center rounded-full bg-[#5c8274] font-mono text-2xs text-white">{currentUser.initials}</div>
<div>
<strong className="block text-xs text-white">{currentUser.name}</strong>
<span className="mt-0.5 block text-3xs text-forest-300">{currentUser.role}</span>
</div>
<span className="ml-auto tracking-[2px] text-[#91aaa0]">•••</span>
</div>
</div>
</aside>
)
}
+15
View File
@@ -0,0 +1,15 @@
// Shared Tailwind class strings for elements reused across pages.
export const panel = 'min-w-0 rounded-lg border border-line bg-white shadow-[0_5px_20px_#1b252305]'
const buttonBase = 'inline-flex cursor-pointer items-center justify-center gap-2 rounded-[5px] px-3.5 py-[11px] text-xs font-bold no-underline'
export const primaryButton = `${buttonBase} bg-coral text-white shadow-[0_4px_12px_#ee725833]`
export const secondaryButton = `${buttonBase} border border-line bg-white text-ink`
export const lightButton = `${buttonBase} bg-[#edf6ef] text-teal`
export const iconButton = 'grid cursor-pointer place-items-center bg-transparent p-1.5 text-[#72817d]'
export const field =
'mt-[7px] block w-full rounded-[5px] border border-line bg-field px-3 py-[11px] text-xs text-ink outline-none focus:border-[#83b3a5] focus:shadow-[0_0_0_3px_#83b3a522]'
export const filterBox = 'flex h-[38px] items-center gap-2 rounded-[5px] border border-line px-[11px] text-[#85938e]'
+59 -6
View File
@@ -1,8 +1,61 @@
@import url('https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=DM+Sans:wght@400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap');
@import "tailwindcss";
:root { font-family: 'DM Sans', sans-serif; color: #1b2523; background: #f7f8f5; font-synthesis: none; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; }
* { box-sizing: border-box; }
body { margin: 0; min-width: 320px; }
button, input, select, textarea { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
@theme {
--font-sans: "DM Sans Variable", ui-sans-serif, system-ui, sans-serif;
--font-mono: "DM Mono", ui-monospace, monospace;
--font-display: "Space Grotesk Variable", ui-sans-serif, system-ui, sans-serif;
--text-3xs: 0.625rem;
--text-2xs: 0.6875rem;
--color-ink: #182522;
--color-body: #53625d;
--color-muted: #71807b;
--color-faint: #9aa6a2;
--color-line: #e2e7e2;
--color-line-soft: #edf0ec;
--color-canvas: #f7f8f5;
--color-field: #fbfcfa;
--color-coral: #ee7258;
--color-teal: #275c55;
--color-sage: #70a59a;
--color-positive: #38a17f;
/* Sidebar */
--color-forest-950: #163c37;
--color-forest-900: #1d4841;
--color-forest-800: #28574f;
--color-forest-700: #315b54;
--color-forest-300: #9bb4ab;
--color-forest-200: #aac0b8;
--color-forest-100: #dce8e0;
/* Tones used for icons, badges and status chips */
--color-coral-soft: #fbe3dd;
--color-coral-strong: #dc634e;
--color-amber-soft: #fff1ca;
--color-amber-strong: #b47a11;
--color-mint-soft: #dcefe4;
--color-mint-strong: #3d9576;
--color-sky-soft: #dfedf1;
--color-sky-strong: #39819c;
}
@layer base {
html {
color: var(--color-ink);
background: var(--color-canvas);
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
}
body {
min-width: 320px;
}
button,
a {
-webkit-tap-highlight-color: transparent;
}
}
+6
View File
@@ -0,0 +1,6 @@
export const APP_NAME = 'Open SafetyLog EHS'
// TODO: point the default at the public git repository once it exists (see docs/TODO.md).
export const SOURCE_URL = import.meta.env.VITE_SOURCE_URL || 'https://www.equineform.com'
export const APP_VERSION = __APP_VERSION__
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest'
import { formatDate, greeting, toIsoDate } from './dates'
describe('dates', () => {
it('formats ISO dates without time-zone drift', () => {
expect(formatDate('2024-08-28')).toBe('Aug 28, 2024')
})
it('converts a local date to an ISO calendar date', () => {
expect(toIsoDate(new Date(2024, 0, 5, 23, 59))).toBe('2024-01-05')
})
it('greets by time of day', () => {
expect(greeting(new Date(2024, 0, 1, 8))).toBe('Good morning')
expect(greeting(new Date(2024, 0, 1, 13))).toBe('Good afternoon')
expect(greeting(new Date(2024, 0, 1, 20))).toBe('Good evening')
})
})
+24
View File
@@ -0,0 +1,24 @@
const displayDate = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' })
const longDate = new Intl.DateTimeFormat('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' })
/** Formats an ISO calendar date (`2024-08-28`) as `Aug 28, 2024`. */
export function formatDate(isoDate: string): string {
return displayDate.format(new Date(`${isoDate}T00:00:00Z`))
}
/** Today's date in the viewer's local time zone as an ISO calendar date. */
export function toIsoDate(date: Date): string {
const pad = (value: number) => String(value).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}
export function formatLongDate(date: Date): string {
return longDate.format(date)
}
export function greeting(date: Date): string {
const hour = date.getHours()
if (hour < 12) return 'Good morning'
if (hour < 18) return 'Good afternoon'
return 'Good evening'
}
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from 'vitest'
import { ALL_TYPES, createIncident, filterIncidents, nextIncidentId } from './incidents'
import { seedIncidents } from './seed'
describe('filterIncidents', () => {
it('returns everything with an empty query and no type filter', () => {
expect(filterIncidents(seedIncidents, '', ALL_TYPES)).toHaveLength(seedIncidents.length)
})
it('matches title, id and location case-insensitively', () => {
expect(filterIncidents(seedIncidents, 'FORKLIFT', ALL_TYPES).map((i) => i.id)).toEqual(['INC-2408'])
expect(filterIncidents(seedIncidents, 'inc-2405', ALL_TYPES).map((i) => i.id)).toEqual(['INC-2405'])
expect(filterIncidents(seedIncidents, 'line 3', ALL_TYPES).map((i) => i.id)).toEqual(['INC-2406'])
})
it('filters by type', () => {
expect(filterIncidents(seedIncidents, '', 'Hazard').map((i) => i.id)).toEqual(['INC-2407'])
})
})
describe('nextIncidentId', () => {
it('increments the highest existing id', () => {
expect(nextIncidentId(seedIncidents)).toBe('INC-2409')
})
it('starts at INC-0001 when there are no incidents', () => {
expect(nextIncidentId([])).toBe('INC-0001')
})
})
describe('createIncident', () => {
it('assigns id, status, date and reporter', () => {
const incident = createIncident(
{ title: 'Spill', type: 'Hazard', severity: 'Low', building: 'Building A', location: 'Dock' },
seedIncidents,
'Alex Kim',
new Date(2026, 9, 6, 9, 30),
)
expect(incident).toMatchObject({ id: 'INC-2409', status: 'New report', date: '2026-10-06', reporter: 'Alex Kim' })
})
})
+47
View File
@@ -0,0 +1,47 @@
import { toIsoDate } from './dates'
import type { Tone } from './tones'
import type { Incident, IncidentStatus, IncidentType, NewIncident, Severity } from './types'
export const ALL_TYPES = 'All incidents'
export type TypeFilter = IncidentType | typeof ALL_TYPES
export function filterIncidents(incidents: Incident[], query: string, type: TypeFilter): Incident[] {
const needle = query.trim().toLowerCase()
return incidents.filter(
(incident) =>
`${incident.title} ${incident.id} ${incident.location}`.toLowerCase().includes(needle) &&
(type === ALL_TYPES || incident.type === type),
)
}
/** Next sequential ID after the highest existing `INC-####`. Temporary until the backend assigns IDs. */
export function nextIncidentId(incidents: Incident[]): string {
const highest = incidents.reduce((max, { id }) => Math.max(max, Number(id.replace(/^INC-/, '')) || 0), 0)
return `INC-${String(highest + 1).padStart(4, '0')}`
}
export const isOpen = (incident: Incident) => incident.status !== 'Resolved'
export const typeTone: Record<IncidentType, Tone> = {
'Near miss': 'amber',
Hazard: 'sky',
Injury: 'coral',
'Property damage': 'mint',
}
export const severityDotClass: Record<Severity, string> = {
High: 'bg-coral-strong',
Medium: 'bg-[#d8a631]',
Low: 'bg-[#52a57e]',
}
export function statusClass(status: IncidentStatus): string {
if (status === 'Resolved') return 'bg-mint-soft text-[#398461]'
if (status === 'Review required') return 'bg-coral-soft text-[#c75e4b]'
return 'bg-[#fff0d2] text-[#9a7319]'
}
/** Builds a full incident record from a submitted report. */
export function createIncident(draft: NewIncident, existing: Incident[], reporter: string, now: Date): Incident {
return { ...draft, id: nextIncidentId(existing), status: 'New report', date: toIsoDate(now), reporter }
}
+23
View File
@@ -0,0 +1,23 @@
import { BarChart3, ClipboardList, LayoutDashboard, MapPin, type LucideIcon } from 'lucide-react'
export interface NavItem {
label: string
to: string
icon: LucideIcon
}
export const primaryNav: NavItem[] = [
{ label: 'Overview', to: '/', icon: LayoutDashboard },
{ label: 'Incidents', to: '/incidents', icon: ClipboardList },
{ label: 'Locations', to: '/locations', icon: MapPin },
{ label: 'Analytics', to: '/analytics', icon: BarChart3 },
]
export const pageTitles: Record<string, string> = {
'/': 'Overview',
'/incidents': 'Incidents',
'/locations': 'Locations',
'/analytics': 'Analytics',
'/report': 'Report an incident',
'/about': 'About',
}
+20
View File
@@ -0,0 +1,20 @@
import type { Incident, Person, Site } from './types'
// Demo data for the UI prototype. Replaced by the API in Phase 1.
export const currentUser: Person = { name: 'Jordan Lee', initials: 'JL', role: 'Safety manager' }
export const workspace = { name: 'Northstar Co.', initials: 'NC' }
export const seedIncidents: Incident[] = [
{ id: 'INC-2408', title: 'Forklift reversed into pallet stack', type: 'Near miss', severity: 'High', status: 'Investigation', building: 'Warehouse 04', location: 'Loading bay C', date: '2024-08-28', reporter: 'Jordan Lee' },
{ id: 'INC-2407', title: 'Wet floor near employee entrance', type: 'Hazard', severity: 'Medium', status: 'Action open', building: 'Building A', location: 'Ground floor lobby', date: '2024-08-27', reporter: 'Maya Chen' },
{ id: 'INC-2406', title: 'Hand laceration during material handling', type: 'Injury', severity: 'High', status: 'Review required', building: 'Fabrication 02', location: 'Line 3', date: '2024-08-26', reporter: 'Sam Rivera' },
{ id: 'INC-2405', title: 'Damaged guardrail on mezzanine', type: 'Property damage', severity: 'Low', status: 'Resolved', building: 'Warehouse 01', location: 'Mezzanine east', date: '2024-08-24', reporter: 'Priya Shah' },
]
export const sites: Site[] = [
{ name: 'North Campus', buildings: ['Building A', 'Warehouse 04', 'Lab 2'], incidentCount: 12 },
{ name: 'South Campus', buildings: ['Fabrication 02', 'Yard', 'Office block'], incidentCount: 7 },
{ name: 'West Campus', buildings: ['Warehouse 01', 'Loading dock'], incidentCount: 5 },
]
+9
View File
@@ -0,0 +1,9 @@
export type Tone = 'coral' | 'amber' | 'mint' | 'sky'
/** Soft background + strong foreground pairs for icon tiles and chips. */
export const toneClasses: Record<Tone, string> = {
coral: 'bg-coral-soft text-coral-strong',
amber: 'bg-amber-soft text-amber-strong',
mint: 'bg-mint-soft text-mint-strong',
sky: 'bg-sky-soft text-sky-strong',
}
+38
View File
@@ -0,0 +1,38 @@
export const incidentTypes = ['Near miss', 'Hazard', 'Injury', 'Property damage'] as const
export type IncidentType = (typeof incidentTypes)[number]
export const severities = ['Low', 'Medium', 'High'] as const
export type Severity = (typeof severities)[number]
export type IncidentStatus = 'New report' | 'Investigation' | 'Action open' | 'Review required' | 'Resolved'
export interface Incident {
id: string
title: string
type: IncidentType
severity: Severity
status: IncidentStatus
site?: string
building: string
location: string
/** ISO calendar date, e.g. `2024-08-28` */
date: string
reporter: string
details?: string
cause?: string
response?: string
}
export type NewIncident = Omit<Incident, 'id' | 'status' | 'date' | 'reporter'>
export interface Site {
name: string
buildings: string[]
incidentCount: number
}
export interface Person {
name: string
initials: string
role: string
}
+17
View File
@@ -0,0 +1,17 @@
import '@fontsource-variable/dm-sans'
import '@fontsource-variable/space-grotesk'
import '@fontsource/dm-mono/400.css'
import '@fontsource/dm-mono/500.css'
import './index.css'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
)
+64
View File
@@ -0,0 +1,64 @@
import { ArrowUpRight, Code2, Scale, ShieldCheck } from 'lucide-react'
import { Eyebrow } from '../components/Eyebrow'
import { Page } from '../components/Page'
import { PageIntro } from '../components/PageIntro'
import { panel, primaryButton } from '../components/styles'
import { APP_NAME, APP_VERSION, SOURCE_URL } from '../lib/config'
const card = `${panel} p-[26px]`
const iconTile = 'mb-5 grid size-[38px] place-items-center rounded-[7px]'
export function About() {
return (
<Page narrow>
<PageIntro
eyebrow={`Version ${APP_VERSION}`}
title={`About ${APP_NAME}`}
copy="Free, open-source accident and safety tracking for manufacturing."
action={
<a className={primaryButton} href={SOURCE_URL} target="_blank" rel="noreferrer">
<Code2 size={17} /> View source code
</a>
}
/>
<div className="grid gap-5">
<section className={card}>
<div className={`${iconTile} bg-coral-soft text-coral-strong`}>
<ShieldCheck size={19} />
</div>
<Eyebrow>Why it exists</Eyebrow>
<h2 className="mt-1.5 mb-2.5 font-display text-[19px] font-semibold">Safety records shouldn’t depend on your budget</h2>
<p className="text-xs leading-[1.6] text-muted">
{APP_NAME} helps plants of any size report incidents and near misses, investigate root causes, follow corrective actions through to
closure, and keep the records regulators expect. You can run it on your own servers, and your data stays with you.
</p>
</section>
<div className="grid gap-5 sm:grid-cols-2">
<section className={card}>
<div className={`${iconTile} bg-sky-soft text-sky-strong`}>
<Scale size={19} />
</div>
<Eyebrow>License</Eyebrow>
<h2 className="mt-1.5 mb-2.5 font-display text-[19px] font-semibold">GNU AGPL v3.0</h2>
<p className="text-xs leading-[1.6] text-muted">
You may use, study, change and share this software. If you run a modified version for others over a network, you must offer them its
source code too.
</p>
</section>
<section className={card}>
<div className={`${iconTile} bg-mint-soft text-mint-strong`}>
<Code2 size={19} />
</div>
<Eyebrow>Source code</Eyebrow>
<h2 className="mt-1.5 mb-2.5 font-display text-[19px] font-semibold">Get the code, contribute</h2>
<p className="mb-4 text-xs leading-[1.6] text-muted">The complete source for this version, plus guides for reporting issues and contributing.</p>
<a className="inline-flex items-center gap-[5px] text-xs font-bold text-coral" href={SOURCE_URL} target="_blank" rel="noreferrer">
{SOURCE_URL.replace(/^https?:\/\//, '')} <ArrowUpRight size={15} />
</a>
</section>
</div>
</div>
</Page>
)
}
+49
View File
@@ -0,0 +1,49 @@
import { ArrowUpRight, Flame } from 'lucide-react'
import { Eyebrow } from '../components/Eyebrow'
import { Page } from '../components/Page'
import { PageIntro } from '../components/PageIntro'
import { ProgressBar } from '../components/ProgressRow'
import { lightButton, panel } from '../components/styles'
const card = 'flex min-h-[240px] flex-col items-start p-[26px]'
const bigStat = 'mt-8 mb-[25px] font-display text-[25px] font-semibold'
const responseTrend = [38, 54, 45, 72, 86, 94]
// Placeholder insights until analytics are computed from real data (Phase 5)
export function Analytics() {
return (
<Page>
<PageIntro eyebrow="Program intelligence" title="Analytics" copy="Patterns that help your team prevent the next incident." />
<div className="grid gap-5 lg:grid-cols-[1.3fr_1fr_1fr]">
<div className={`${card} rounded-lg border border-forest-900 bg-forest-900 text-[#dfece5] shadow-[0_5px_20px_#1b252305]`}>
<Flame size={22} />
<Eyebrow className="mt-4 text-[#9dc0b3]">Top signal</Eyebrow>
<h2 className="mt-5 mb-2.5 font-display text-2xl leading-[1.15] font-semibold">Material handling is your highest-risk activity.</h2>
<p className="mb-4 text-xs leading-[1.6] text-[#a7c0b8]">42% of incidents in the last 90 days relate to movement or storage of materials.</p>
<button type="button" className={`${lightButton} mt-auto`}>
View contributing incidents <ArrowUpRight size={16} />
</button>
</div>
<div className={`${panel} ${card}`}>
<Eyebrow>Most common root cause</Eyebrow>
<strong className={bigStat}>Inadequate guarding</strong>
<div className="flex w-full justify-between text-2xs text-muted">
<span>8 incidents</span>
<span>31% of total</span>
</div>
<ProgressBar percent={31} className="mt-2.5 w-full" />
</div>
<div className={`${panel} ${card}`}>
<Eyebrow>Response quality</Eyebrow>
<strong className={bigStat}>94%</strong>
<p className="text-xs leading-[1.6] text-muted">of corrective actions are completed on time.</p>
<div className="mt-auto flex h-[70px] w-full items-end gap-[7px] pt-4">
{responseTrend.map((height, index) => (
<i key={index} className="min-h-[15px] flex-1 rounded-t-[3px] bg-[#76a99d]" style={{ height: `${height}%` }} />
))}
</div>
</div>
</div>
</Page>
)
}
+62
View File
@@ -0,0 +1,62 @@
import { FileText, Filter, Plus, Search } from 'lucide-react'
import { useState } from 'react'
import { NavLink } from 'react-router-dom'
import { IncidentTable } from '../components/IncidentTable'
import { Page } from '../components/Page'
import { PageIntro } from '../components/PageIntro'
import { filterBox, panel, primaryButton, secondaryButton } from '../components/styles'
import { ALL_TYPES, filterIncidents, type TypeFilter } from '../lib/incidents'
import { incidentTypes, type Incident } from '../lib/types'
export function Incidents({ incidents }: { incidents: Incident[] }) {
const [query, setQuery] = useState('')
const [type, setType] = useState<TypeFilter>(ALL_TYPES)
const filtered = filterIncidents(incidents, query, type)
return (
<Page>
<PageIntro
eyebrow="Safety register"
title="Incidents"
copy="A complete record of reported events, hazards, and learnings."
action={
<NavLink className={primaryButton} to="/report">
<Plus size={17} /> Report incident
</NavLink>
}
/>
<section className={`${panel} overflow-hidden`}>
<div className="flex flex-wrap items-center gap-2.5 border-b border-line px-[17px] py-3.5 sm:flex-nowrap sm:px-6 sm:py-[18px]">
<div className={`${filterBox} basis-full sm:max-w-[350px] sm:flex-1 sm:basis-auto`}>
<Search size={17} />
<input
className="w-full bg-transparent text-xs text-ink outline-none"
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder="Search incidents"
aria-label="Search incidents"
/>
</div>
<div className={`${filterBox} sm:ml-auto`}>
<Filter size={16} />
<select
className="bg-transparent text-xs text-ink outline-none"
value={type}
onChange={(event) => setType(event.target.value as TypeFilter)}
aria-label="Filter by type"
>
<option>{ALL_TYPES}</option>
{incidentTypes.map((option) => (
<option key={option}>{option}</option>
))}
</select>
</div>
<button type="button" className={secondaryButton}>
<FileText size={16} /> Export
</button>
</div>
<IncidentTable incidents={filtered} wide />
</section>
</Page>
)
}
+70
View File
@@ -0,0 +1,70 @@
import { Building2, ChevronDown, MapPin, Plus } from 'lucide-react'
import { Page } from '../components/Page'
import { PageIntro } from '../components/PageIntro'
import { PanelHeading } from '../components/PanelHeading'
import { panel, primaryButton } from '../components/styles'
import { sites } from '../lib/seed'
import { toneClasses, type Tone } from '../lib/tones'
const siteTones: Tone[] = ['coral', 'amber', 'sky']
const mapPin = 'absolute size-3.5 rounded-full border-[3px] border-white bg-coral shadow-[0_2px_5px_#275c5550]'
export function Locations() {
return (
<Page>
<PageIntro
eyebrow="Site map"
title="Locations"
copy="Understand incident patterns across every level of your workplace."
action={
<button type="button" className={primaryButton}>
<Plus size={17} /> Add location
</button>
}
/>
<div className="grid gap-5 lg:grid-cols-2">
<section className={panel}>
<PanelHeading eyebrow="Sites" title="Location register" />
{sites.map((site, index) => (
<div key={site.name} className="flex items-center gap-[13px] border-t border-line px-6 py-[18px]">
<div className={`grid size-[38px] place-items-center rounded-[7px] ${toneClasses[siteTones[index % siteTones.length]]}`}>
<Building2 size={19} />
</div>
<div className="flex-1">
<strong className="block text-[13px]">{site.name}</strong>
<span className="mt-1 block text-2xs text-muted">{site.buildings.join(', ')}</span>
</div>
<b className="font-mono text-[15px] font-normal">
{site.incidentCount}
<small className="font-sans text-3xs text-muted"> incidents</small>
</b>
<ChevronDown size={16} className="text-muted" />
</div>
))}
</section>
{/* Map placeholder until a real site map is built */}
<section className={`${panel} relative min-h-[360px] overflow-hidden bg-[#e3eee7]`}>
<div
className="absolute inset-0 scale-140 rotate-12 opacity-45"
style={{
backgroundImage:
'linear-gradient(30deg, transparent 47%, #b1cfc0 48%, transparent 49%), linear-gradient(115deg, transparent 47%, #b1cfc0 48%, transparent 49%)',
backgroundSize: '80px 80px',
}}
/>
<div className="absolute bottom-[27px] left-7 rounded-md bg-white px-3.5 py-[11px] shadow-[0_5px_15px_#275c5520]">
<div className="flex items-center gap-[5px]">
<MapPin size={17} className="text-coral" />
<strong className="text-xs">North Campus</strong>
</div>
<span className="mt-1 block text-3xs text-muted">12 incidents this year</span>
</div>
<i className={`${mapPin} top-[30%] left-[40%]`} />
<i className={`${mapPin} top-[48%] left-[64%]`} />
<i className={`${mapPin} top-[65%] left-[24%]`} />
</section>
</div>
</Page>
)
}
+87
View File
@@ -0,0 +1,87 @@
import { Bell, CheckCircle2, Plus, ShieldCheck, Siren } from 'lucide-react'
import { NavLink } from 'react-router-dom'
import { IncidentTable } from '../components/IncidentTable'
import { MetricCard } from '../components/MetricCard'
import { Page } from '../components/Page'
import { PageIntro } from '../components/PageIntro'
import { PanelHeading } from '../components/PanelHeading'
import { ProgressRow } from '../components/ProgressRow'
import { panel, primaryButton } from '../components/styles'
import { formatLongDate, greeting } from '../lib/dates'
import { currentUser } from '../lib/seed'
import type { Incident } from '../lib/types'
const trendPath =
'M0,142 C30,132 42,146 69,130 S105,116 131,126 S166,110 191,120 S225,103 250,115 S285,89 314,103 S355,104 380,85 S412,100 439,72 S468,88 498,61 S530,71 555,52 S590,65 620,32'
export function Overview({ incidents }: { incidents: Incident[] }) {
const now = new Date()
return (
<Page>
<PageIntro
eyebrow={formatLongDate(now)}
title={`${greeting(now)}, ${currentUser.name.split(' ')[0]}`}
copy="Here’s what’s happening across your safety program."
action={
<NavLink className={primaryButton} to="/report">
<Plus size={17} /> Report incident
</NavLink>
}
/>
{/* Placeholder figures until metrics are computed from real data (Phase 2) */}
<div className="mb-5 grid grid-cols-2 gap-[9px] sm:gap-[13px] lg:grid-cols-4">
<MetricCard label="Open incidents" value="18" delta="3 from last week" icon={Siren} tone="coral" />
<MetricCard label="Due this week" value="07" delta="2 due today" icon={Bell} tone="amber" />
<MetricCard label="Avg. close time" value="4.2d" delta="0.8d faster" icon={CheckCircle2} tone="mint" />
<MetricCard label="Program health" value="92%" delta="Up 4% this month" icon={ShieldCheck} tone="sky" />
</div>
<div className="mb-5 grid gap-5 lg:grid-cols-[minmax(0,1.7fr)_minmax(260px,0.8fr)]">
<section className={`${panel} overflow-hidden`}>
<PanelHeading eyebrow="Needs attention" title="Recent incidents" link={{ label: 'View all', to: '/incidents' }} />
<IncidentTable incidents={incidents} limit={5} />
</section>
<section className={`${panel} pb-[18px]`}>
<PanelHeading eyebrow="Response progress" title="Open actions" />
<div className="mx-auto mt-3 mb-5 grid size-[126px] rotate-[28deg] place-items-center rounded-full border-[10px] border-[#e8f0e9] border-t-coral border-r-coral">
<div className="-rotate-[28deg] text-center">
<strong className="block font-display text-[25px] font-semibold">68%</strong>
<span className="text-3xs text-muted">complete</span>
</div>
</div>
<ProgressRow label="Root cause review" value="8 / 12" percent={66} />
<ProgressRow label="Corrective actions" value="14 / 21" percent={67} />
<ProgressRow label="Team sign-offs" value="28 / 32" percent={87} />
</section>
</div>
<div className="grid gap-5 lg:grid-cols-[1.3fr_0.9fr]">
<section className={`${panel} min-h-[260px]`}>
<PanelHeading eyebrow="Signal check" title="Incident trend" />
<div className="relative mx-[25px] mt-1 mb-[22px] h-[170px]">
<div className="absolute inset-0" style={{ background: 'repeating-linear-gradient(to bottom, transparent 0, transparent 41px, #edf0ec 42px)' }} />
<svg className="absolute inset-0 size-full" viewBox="0 0 620 190" preserveAspectRatio="none" aria-label="Incident trend">
<path d={trendPath} fill="none" stroke="var(--color-coral)" strokeWidth="3" />
<path d={`${trendPath} L620,190 L0,190Z`} fill="var(--color-coral)" opacity=".12" />
</svg>
<div className="absolute right-0 -bottom-5 left-0 flex justify-between font-mono text-3xs text-[#a0aba7]">
<span>Aug 01</span>
<span>Aug 08</span>
<span>Aug 15</span>
<span>Aug 22</span>
<span>Aug 29</span>
</div>
</div>
</section>
<section className={panel}>
<PanelHeading eyebrow="By location" title="Where incidents happen" link={{ label: 'Explore', to: '/locations' }} />
<ProgressRow variant="location" label="North Campus" value="12" percent={82} />
<ProgressRow variant="location" label="South Campus" value="7" percent={52} />
<ProgressRow variant="location" label="West Campus" value="5" percent={38} />
<ProgressRow variant="location" label="Remote / other" value="3" percent={24} />
</section>
</div>
</Page>
)
}
+131
View File
@@ -0,0 +1,131 @@
import { ArrowUpRight } from 'lucide-react'
import { useState, type ChangeEvent, type FormEvent } from 'react'
import { NavLink, useNavigate } from 'react-router-dom'
import { Field, FormSection } from '../components/FormSection'
import { Page } from '../components/Page'
import { PageIntro } from '../components/PageIntro'
import { field, panel, primaryButton, secondaryButton } from '../components/styles'
import { sites } from '../lib/seed'
import { incidentTypes, severities, type NewIncident } from '../lib/types'
const emptyReport: NewIncident = {
title: '',
type: 'Near miss',
severity: 'Medium',
site: sites[0].name,
building: sites[0].buildings[0],
location: '',
details: '',
cause: '',
response: '',
}
export function ReportIncident({ onSubmit }: { onSubmit: (report: NewIncident) => void }) {
const navigate = useNavigate()
const [form, setForm] = useState<NewIncident>(emptyReport)
const buildings = sites.find((site) => site.name === form.site)?.buildings ?? []
const update = (key: keyof NewIncident) => (event: ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) =>
setForm({ ...form, [key]: event.target.value })
const changeSite = (event: ChangeEvent<HTMLSelectElement>) => {
const site = event.target.value
setForm({ ...form, site, building: sites.find((s) => s.name === site)?.buildings[0] ?? '' })
}
const submit = (event: FormEvent) => {
event.preventDefault()
if (!form.title.trim() || !form.location.trim()) return
onSubmit(form)
navigate('/incidents')
}
return (
<Page narrow>
<PageIntro eyebrow="New report" title="Report an incident" copy="Capture the facts while they are fresh. You can add investigation details later." />
<form className={`${panel} overflow-hidden`} onSubmit={submit}>
<FormSection number="01" title="What happened?" copy="Start with a clear, factual description.">
<Field label="Incident title">
<input className={field} required value={form.title} onChange={update('title')} placeholder="e.g. Slip near loading dock" />
</Field>
<div className="grid sm:grid-cols-2 sm:gap-[18px]">
<Field label="Incident type">
<select className={field} value={form.type} onChange={update('type')}>
{incidentTypes.map((option) => (
<option key={option}>{option}</option>
))}
</select>
</Field>
<Field label="Severity">
<select className={field} value={form.severity} onChange={update('severity')}>
{severities.map((option) => (
<option key={option}>{option}</option>
))}
</select>
</Field>
</div>
<Field label="What happened?" optional>
<textarea
className={`${field} resize-y`}
value={form.details}
onChange={update('details')}
placeholder="Describe what you observed, without assumptions..."
rows={4}
/>
</Field>
</FormSection>
<FormSection number="02" title="Where did it happen?" copy="Pinpoint the location so patterns become visible.">
<div className="grid sm:grid-cols-2 sm:gap-[18px]">
<Field label="Site">
<select className={field} value={form.site} onChange={changeSite}>
{sites.map((site) => (
<option key={site.name}>{site.name}</option>
))}
</select>
</Field>
<Field label="Building">
<select className={field} value={form.building} onChange={update('building')}>
{buildings.map((building) => (
<option key={building}>{building}</option>
))}
</select>
</Field>
</div>
<Field label="Specific location">
<input className={field} required value={form.location} onChange={update('location')} placeholder="e.g. Ground floor lobby, Line 3" />
</Field>
</FormSection>
<FormSection number="03" title="Response & root cause" copy="Add what you know now. These can be refined during investigation.">
<Field label="Immediate response" optional>
<textarea
className={`${field} resize-y`}
value={form.response}
onChange={update('response')}
placeholder="e.g. Area isolated, supervisor notified..."
rows={3}
/>
</Field>
<Field label="Suspected root cause" optional>
<input className={field} value={form.cause} onChange={update('cause')} placeholder="e.g. Inadequate guarding" />
</Field>
</FormSection>
<div className="flex flex-col items-end gap-[15px] px-5 py-[17px] text-2xs text-muted sm:flex-row sm:items-center sm:justify-between sm:px-9 sm:py-5">
<span>
<span className="mr-1.5 text-[#3d9c7e]">✓</span>Save a draft at any time.
</span>
<div className="flex w-full justify-end gap-[9px] sm:w-auto">
<NavLink to="/" className={secondaryButton}>
Cancel
</NavLink>
<button className={primaryButton} type="submit">
Submit report <ArrowUpRight size={16} />
</button>
</div>
</div>
</form>
</Page>
)
}
+5
View File
@@ -0,0 +1,5 @@
import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach } from 'vitest'
afterEach(() => cleanup())
+8
View File
@@ -0,0 +1,8 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
/** Public URL of this deployment's source code (AGPL-3.0 section 13). */
readonly VITE_SOURCE_URL?: string
}
declare const __APP_VERSION__: string
+22
View File
@@ -0,0 +1,22 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"types": ["vite/client", "vitest/globals", "@testing-library/jest-dom/vitest"],
"jsx": "react-jsx",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"skipLibCheck": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}
+4
View File
@@ -0,0 +1,4 @@
{
"files": [],
"references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }]
}
+19
View File
@@ -0,0 +1,19 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
"types": ["node"],
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"skipLibCheck": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["vite.config.ts", "playwright.config.ts", "e2e"]
}
+19
View File
@@ -0,0 +1,19 @@
/// <reference types="vitest/config" />
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import { readFileSync } from 'node:fs'
import { defineConfig } from 'vite'
const { version } = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) as { version: string }
// https://vite.dev/config/
export default defineConfig({
plugins: [react(), tailwindcss()],
define: { __APP_VERSION__: JSON.stringify(version) },
test: {
environment: 'jsdom',
globals: true,
setupFiles: ['./src/test/setup.ts'],
include: ['src/**/*.test.{ts,tsx}'],
},
})