This commit is contained in:
Hein 2025-09-19 14:06:53 +02:00
commit 46dabed765
55 changed files with 9856 additions and 0 deletions

8
.changeset/README.md Normal file
View File

@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)

11
.changeset/config.json Normal file
View File

@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.1.1/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": true,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}

27
.gitignore vendored Normal file
View File

@ -0,0 +1,27 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*storybook.log
storybook-static

35
.prettierrc.mjs Normal file
View File

@ -0,0 +1,35 @@
// /** @type {import("@ianvs/prettier-plugin-sort-imports").PrettierConfig} */
const config = {
printWidth: 100,
singleQuote: true,
trailingComma: 'es5',
// plugins: ['@ianvs/prettier-plugin-sort-imports'],
importOrder: [
'.*styles.css$',
'',
'dayjs',
'^react$',
'^next$',
'^next/.*$',
'<BUILTIN_MODULES>',
'<THIRD_PARTY_MODULES>',
'^@mantine/(.*)$',
'^@mantinex/(.*)$',
'^@mantine-tests/(.*)$',
'^@docs/(.*)$',
'^@/.*$',
'^../(?!.*.css$).*$',
'^./(?!.*.css$).*$',
'\\.css$',
],
overrides: [
{
files: '*.mdx',
options: {
printWidth: 70,
},
},
],
};
export default config;

13
.storybook/main.ts Normal file
View File

@ -0,0 +1,13 @@
import type { StorybookConfig } from '@storybook/react-vite';
const config: StorybookConfig = {
"stories": [
"../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"
],
"addons": [],
"framework": {
"name": "@storybook/react-vite",
"options": {}
}
};
export default config;

18
.storybook/preview.ts Normal file
View File

@ -0,0 +1,18 @@
import type { Preview } from '@storybook/react-vite'
import { PreviewDecorator } from './previewDecorator';
const preview: Preview = {
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
decorators: [
PreviewDecorator,
],
};
export default preview;

View File

@ -0,0 +1,13 @@
import { MantineProvider } from '@mantine/core';
import '@mantine/core/styles.css';
export function PreviewDecorator(Story: any, { parameters }: any) {
console.log('Rendering decorator', parameters);
return (
<MantineProvider>
<div style={{ height: 'calc(100vh - 64px)', width: 'calc(100vw - 64px)' }}>
<Story key={'mainStory'} />
</div>
</MantineProvider>
);
}

1
.stylelintcache Normal file
View File

@ -0,0 +1 @@
[["1"],{"key":"2","value":"3"},"/home/hein/hein/dev/Gridler/src/components/Gridler/Gridler.module.css",{"size":609,"mtime":1757930699397,"data":"4"},{"hashOfConfig":"5"},"ijgzra"]

1
.stylelintignore Normal file
View File

@ -0,0 +1 @@
dist

28
.stylelintrc.json Normal file
View File

@ -0,0 +1,28 @@
{
"extends": ["stylelint-config-standard-scss"],
"rules": {
"custom-property-pattern": null,
"selector-class-pattern": null,
"scss/no-duplicate-mixins": null,
"declaration-empty-line-before": null,
"declaration-block-no-redundant-longhand-properties": null,
"alpha-value-notation": null,
"custom-property-empty-line-before": null,
"property-no-vendor-prefix": null,
"color-function-notation": null,
"length-zero-no-unit": null,
"selector-not-notation": null,
"no-descending-specificity": null,
"comment-empty-line-before": null,
"scss/at-mixin-pattern": null,
"scss/at-rule-no-unknown": null,
"value-keyword-case": null,
"media-feature-range-notation": null,
"selector-pseudo-class-no-unknown": [
true,
{
"ignorePseudoClasses": ["global"]
}
]
}
}

13
CHANGELOG.md Normal file
View File

@ -0,0 +1,13 @@
# @warkypublic/zustandsyncstore
## 0.0.2
### Patch Changes
- 2ea6dd5: Fixed export and type mappings
## 0.0.1
### Patch Changes
- 0ed2a54: First Release

339
LICENSE Normal file
View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
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
this service 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.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey 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 General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

204
README.md Normal file
View File

@ -0,0 +1,204 @@
# @warkypublic/oranguru
A React component library providing enhanced Mantine-based components with advanced features and state management capabilities.
## Overview
Oranguru is a comprehensive component library that extends Mantine's component ecosystem. Named after the wise Orangutan Pokémon known for its intelligence and strategic thinking, this library provides enhanced components with advanced positioning, custom rendering, and sophisticated state management capabilities.
Currently featuring advanced menu components, Oranguru is designed to grow into a full suite of enhanced Mantine components that offer more flexibility and power than their standard counterparts.
## Features
### Current Components
- **Enhanced Context Menus**: Better menu positioning and visibility control
- **Custom Rendering**: Support for custom menu item renderers and complete menu rendering
- **Async Actions**: Built-in support for async menu item actions with loading states
### Core Features
- **State Management**: Zustand-based store for component state management
- **TypeScript Support**: Full TypeScript definitions included
- **Portal-based Rendering**: Proper z-index handling through React portals
- **Extensible Architecture**: Designed to support additional Mantine component enhancements
## Installation
```bash
npm install @warkypublic/oranguru
```
### Peer Dependencies
This package requires the following peer dependencies:
```bash
npm install react@">= 19.0.0" zustand@">= 5.0.0" @mantine/core@"^8.3.1" @mantine/hooks@"^8.3.1" @warkypublic/artemis-kit@"^1.0.10" @warkypublic/zustandsyncstore@"^0.0.2" use-sync-external-store@">= 1.4.0"
```
## Usage
### Basic Setup
```tsx
import { MantineBetterMenusProvider } from '@warkypublic/oranguru';
import { MantineProvider } from '@mantine/core';
function App() {
return (
<MantineProvider>
<MantineBetterMenusProvider>
{/* Your app content */}
</MantineBetterMenusProvider>
</MantineProvider>
);
}
```
### Using the Menu Hook
```tsx
import { useMantineBetterMenus } from '@warkypublic/oranguru';
function MyComponent() {
const { show, hide } = useMantineBetterMenus();
const handleContextMenu = (e: React.MouseEvent) => {
e.preventDefault();
show('my-menu', {
x: e.clientX,
y: e.clientY,
items: [
{
label: 'Edit',
onClick: () => console.log('Edit clicked')
},
{
label: 'Delete',
onClick: () => console.log('Delete clicked')
},
{
isDivider: true
},
{
label: 'Async Action',
onClickAsync: async () => {
await new Promise(resolve => setTimeout(resolve, 2000));
console.log('Async action completed');
}
}
]
});
};
return (
<div onContextMenu={handleContextMenu}>
Right-click me for a context menu
</div>
);
}
```
### Custom Menu Items
```tsx
const customMenuItem = {
renderer: ({ loading }: any) => (
<div style={{ padding: '8px 12px' }}>
{loading ? 'Loading...' : 'Custom Item'}
</div>
)
};
show('custom-menu', {
x: e.clientX,
y: e.clientY,
items: [customMenuItem]
});
```
## API Reference
### MantineBetterMenusProvider
The main provider component that wraps your application.
**Props:**
- `providerID?`: Optional unique identifier for the provider instance
### useMantineBetterMenus
Hook to access menu functionality.
**Returns:**
- `show(id: string, options?: Partial<MantineBetterMenuInstance>)`: Show a menu
- `hide(id: string)`: Hide a menu
- `menus`: Array of current menu instances
- `setInstanceState`: Update specific menu instance properties
### MantineBetterMenuInstance
Interface for menu instances:
```typescript
interface MantineBetterMenuInstance {
id: string;
items?: Array<MantineBetterMenuInstanceItem>;
menuProps?: MenuProps;
renderer?: ReactNode;
visible: boolean;
x: number;
y: number;
}
```
### MantineBetterMenuInstanceItem
Interface for menu items:
```typescript
interface MantineBetterMenuInstanceItem extends Partial<MenuItemProps> {
isDivider?: boolean;
label?: string;
onClick?: (e?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
onClickAsync?: () => Promise<void>;
renderer?: ((props: MantineBetterMenuInstanceItem & Record<string, unknown>) => ReactNode) | ReactNode;
}
```
## Development
### Scripts
- `pnpm dev`: Start development server
- `pnpm build`: Build the library
- `pnpm lint`: Run ESLint
- `pnpm typecheck`: Run TypeScript type checking
- `pnpm clean`: Clean node_modules and dist folders
### Building
The library is built using Vite and outputs both ESM and CommonJS formats:
- ESM: `dist/lib.es.js`
- CommonJS: `dist/lib.cjs.js`
- Types: `dist/lib.d.ts`
## License
See [LICENSE](LICENSE) file for details.
## About the Name
Oranguru is named after the Orangutan Pokémon (オランガ Oranga), a Normal/Psychic-type Pokémon introduced in Generation VII. Known as the "Sage Pokémon," Oranguru is characterized by its wisdom, intelligence, and ability to use tools strategically.
In the Pokémon world, Oranguru is known for:
- Its exceptional intelligence and strategic thinking
- Living deep in forests and rarely showing itself to humans
- Using its psychic powers to control other Pokémon with its fan
- Being highly territorial but also caring for other Pokémon in its domain
Just as Oranguru the Pokémon enhances and controls its environment with wisdom and strategic tools, this library aims to enhance and extend Mantine components with intelligent, well-designed solutions.
## Author
**Warky Devs**

34
eslint.config.js Normal file
View File

@ -0,0 +1,34 @@
// For more info, see https://github.com/storybookjs/eslint-plugin-storybook#configuration-flat-config-format
import storybook from 'eslint-plugin-storybook';
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
import perfectionist from 'eslint-plugin-perfectionist';
import { globalIgnores } from 'eslint/config';
export default tseslint.config(
[
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs['recommended-latest'],
reactRefresh.configs.vite,
perfectionist.configs['recommended-alphabetical'],
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
},
},
],
storybook.configs['flat/recommended']
);

92
package.json Normal file
View File

@ -0,0 +1,92 @@
{
"name": "@warkypublic/oranguru",
"author": "Warky Devs",
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint ./src",
"typecheck": "tsc --noEmit",
"clean": "rm -rf node_modules && rm -rf dist ",
"preview": "vite preview",
"storybook": "storybook dev -p 6006",
"build-storybook": "storybook build"
},
"files": [
"dist/**",
"assets/**",
"public/**",
"global.d.ts"
],
"module": "./src.lib.ts",
"types": "./src/lib.ts",
"publishConfig": {
"main": "./dist/lib.cjs.js",
"module": "./dist/lib.es.js",
"require": "./dist/lib.cjs.js",
"types": "./dist/lib.d.ts",
"typings": "./dist/lib.d.ts",
"exports": {
".": {
"import": "./dist/lib.es.js",
"types": "./dist/lib.d.ts",
"default": "./dist/lib.cjs.js"
},
"./package.json": "./package.json"
}
},
"exports": {
".": {
"types": "./src/lib.ts",
"default": "./src/lib.ts"
}
},
"dependencies": {
"@glideapps/glide-data-grid": "^6.0.3",
"@mantine/notifications": "^8.3.1",
"@tabler/icons-react": "^3.35.0",
"@tanstack/react-query": "^5.89.0",
"immer": "^10.1.3",
"moment": "^2.30.1",
"postcss": "^8.5.6",
"postcss-preset-mantine": "^1.18.0",
"postcss-simple-vars": "^7.0.1"
},
"devDependencies": {
"@changesets/cli": "^2.29.7",
"@eslint/js": "^9.35.0",
"@storybook/react-vite": "^9.1.7",
"@types/node": "^24.4.0",
"@types/react": "^19.1.13",
"@types/react-dom": "^19.1.9",
"@typescript-eslint/parser": "^8.43.0",
"@vitejs/plugin-react-swc": "^4.0.1",
"eslint": "^9.35.0",
"eslint-config-mantine": "^4.0.3",
"eslint-plugin-perfectionist": "^4.15.0",
"eslint-plugin-react-hooks": "^5.2.0",
"eslint-plugin-react-refresh": "^0.4.20",
"eslint-plugin-storybook": "^9.1.7",
"global": "^4.4.0",
"globals": "^16.4.0",
"prettier": "^3.6.2",
"prettier-eslint": "^16.4.2",
"react-dom": "^19.1.1",
"storybook": "^9.1.7",
"typescript": "~5.9.2",
"typescript-eslint": "^8.43.0",
"vite": "^7.1.5",
"vite-plugin-dts": "^4.5.4",
"vite-tsconfig-paths": "^5.1.4"
},
"peerDependencies": {
"@mantine/core": "^8.3.1",
"@mantine/hooks": "^8.3.1",
"@warkypublic/artemis-kit": "^1.0.10",
"@warkypublic/zustandsyncstore": "^0.0.2",
"react": ">= 19.0.0",
"use-sync-external-store": ">= 1.4.0",
"zustand": ">= 5.0.0"
}
}

6791
pnpm-lock.yaml Normal file

File diff suppressed because it is too large Load Diff

14
postcss.config.cjs Normal file
View File

@ -0,0 +1,14 @@
module.exports = {
plugins: {
'postcss-preset-mantine': {},
'postcss-simple-vars': {
variables: {
'mantine-breakpoint-xs': '36em',
'mantine-breakpoint-sm': '48em',
'mantine-breakpoint-md': '62em',
'mantine-breakpoint-lg': '75em',
'mantine-breakpoint-xl': '88em',
},
},
},
};

1
public/vite.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1,21 @@
.container {
box-shadow:
1px 0 0 #00000030,
0 1px 0 #00000030,
-1px 0 0 #00000030;
display: flex;
min-height: 50px;
min-width: 50px;
height: 100%;
width: 100%;
&[data-focused='true'] {
box-shadow:
-1px 0px 0px 0px
light-dark(alpha(var(--mantine-color-blue-9), 0.6), alpha(var(--mantine-color-blue-9), 0.3)),
1px 0px 0px 0px
light-dark(alpha(var(--mantine-color-blue-9), 0.6), alpha(var(--mantine-color-blue-9), 0.3)),
0px 1px 0px 0px
light-dark(alpha(var(--mantine-color-blue-9), 0.6), alpha(var(--mantine-color-blue-9), 0.3));
}
}

25
src/Gridler/Gridler.tsx Normal file
View File

@ -0,0 +1,25 @@
import '@glideapps/glide-data-grid/dist/index.css';
import React from 'react';
import { MantineBetterMenusProvider } from '../MantineBetterMenu';
import { type GridlerProps, Provider } from './components/Store';
import { GridlerDataGrid } from './GridlerDataGrid';
export const Gridler = (props: GridlerProps) => {
return (
<MantineBetterMenusProvider>
<Provider
{...props}
persist={{
name: `Gridler_${props.uniqueid}`,
partialize: (s) => ({ colOrder: s.colOrder, colSize: s.colSize }),
version: 1,
}}
>
<GridlerDataGrid />
{props.children}
</Provider>
</MantineBetterMenusProvider>
);
};

View File

@ -0,0 +1,172 @@
import '@glideapps/glide-data-grid/dist/index.css';
import { DataEditor, type DataEditorRef, type GridColumn } from '@glideapps/glide-data-grid';
import { ActionIcon } from '@mantine/core';
import { useElementSize, useMergedRef } from '@mantine/hooks';
import { IconMenu2 } from '@tabler/icons-react';
import React from 'react';
import { Computer } from './components/Computer';
import { Pager } from './components/Pager';
import { SortSprite } from './components/sprites/Sort';
import { SortDownSprite } from './components/sprites/SortDown';
import { SortUpSprite } from './components/sprites/SortUp';
import { useStore } from './components/Store';
import classes from './Gridler.module.css';
import { useGridTheme } from './hooks/use-grid-theme';
export const GridlerDataGrid = () => {
const ref = React.useRef<DataEditorRef | null>(null);
const refContextActivated = React.useRef<boolean>(false);
const { ref: refWrapper, width } = useElementSize();
const {
focused,
getCellContent,
getCellsForSelection,
hasLocalData,
headerHeight,
mounted,
onCellEdited,
onColumnMoved,
onColumnProposeMove,
onColumnResize,
onContextClick,
onHeaderClicked,
onHeaderMenuClick,
onVisibleRegionChanged,
renderColumns,
rowHeight,
setStateFN,
total_rows,
} = useStore((s) => ({
focused: s.focused,
getCellContent: s.getCellContent,
getCellsForSelection: s.getCellsForSelection,
hasLocalData: s.hasLocalData,
headerHeight: s.headerHeight,
mounted: s.mounted,
onCellEdited: s.onCellEdited,
onColumnMoved: s.onColumnMoved,
onColumnProposeMove: s.onColumnProposeMove,
onColumnResize: s.onColumnResize,
onContextClick: s.onContextClick,
onHeaderClicked: s.onHeaderClicked,
onHeaderMenuClick: s.onHeaderMenuClick,
onVisibleRegionChanged: s.onVisibleRegionChanged,
renderColumns: s.renderColumns,
rowHeight: s.rowHeight,
setStateFN: s.setStateFN,
total_rows: s.total_rows,
}));
const refMerged = useMergedRef(ref, (r) => {
setStateFN('_glideref', () => {
return r ?? undefined;
});
});
// const args = useAsyncDataSource<string[]>(
// pageSize ?? 50,
// maxConcurrency ?? 1,
// getRowData,
// toCell,
// onEdited,
// ref
// );
const theme = useGridTheme();
if (!mounted) {
return <>Loadings...<Computer /></>;
}
return (
<div
className={classes.container}
data-focused={focused}
onContextMenu={(e) => {
e.preventDefault();
//Yes this is a litle hacky, but it works to prevent double context menu
if (!refContextActivated.current) {
refContextActivated.current = true;
onContextClick('other', e);
setTimeout(() => {
refContextActivated.current = false;
}, 100);
}
}}
ref={refWrapper}
>
<DataEditor
cellActivationBehavior="double-click"
//getCelrefMergedlContent={getCellContent}
columns={(renderColumns as Array<GridColumn>) ?? []}
columnSelect="none"
drawFocusRing
getCellContent={getCellContent}
getCellsForSelection={getCellsForSelection}
getRowThemeOverride={theme.getRowThemeOverride}
headerHeight={headerHeight ?? 32}
headerIcons={{ sort: SortSprite, sortdown: SortDownSprite, sortup: SortUpSprite }}
height={width}
onCellContextMenu={(cell, event) => {
event.preventDefault();
if (!refContextActivated.current) {
refContextActivated.current = true;
onContextClick('cell', event, cell[0], cell[1]);
setTimeout(() => {
refContextActivated.current = false;
}, 100);
}
}}
onCellEdited={onCellEdited}
onColumnMoved={onColumnMoved}
onColumnProposeMove={onColumnProposeMove}
onColumnResize={onColumnResize}
onHeaderClicked={onHeaderClicked}
onHeaderContextMenu={(col, event) => {
event.preventDefault();
if (!refContextActivated.current) {
refContextActivated.current = true;
onContextClick('header', event, col);
setTimeout(() => {
refContextActivated.current = false;
}, 100);
}
}}
onHeaderMenuClick={onHeaderMenuClick}
onVisibleRegionChanged={onVisibleRegionChanged}
rangeSelect="none"
ref={refMerged as any}
rightElement={
<ActionIcon mr="xs" mt="2px" onClick={(e) => onContextClick('menu', e)} variant="subtle">
<IconMenu2 />
</ActionIcon>
}
rowHeight={rowHeight ?? 22}
rows={total_rows}
// onGridSelectionChange={(sel) => {
// console.log("Selection",sel);
// }}
// onItemHovered={(item) => {
// console.log('Hovered', item);
// }}
//showSearch={true}
// rowMarkers={{
// kind: 'clickable-number',
// width: 30
// }}
rowSelect="multi"
spanRangeBehavior="default"
theme={theme.gridTheme}
width="100%"
/>
{/* <Portal> */}
<div id="portal" />
{/* </Portal> */}
<Computer />
{!hasLocalData && <Pager />}
</div>
);
};

View File

@ -0,0 +1,86 @@
import React, { useEffect } from 'react';
import { APIOptions } from '../../utils/types';
import { useStore } from './Store';
//The computer component does not need to be recalculated on every render, so we use React.memo to prevent unnecessary re-renders.
export const APIAdaptorGoLangv2 = React.memo((props: APIOptions) => {
const [setStateFN, setState, getState, addError, mounted] = useStore((s) => [
s.setStateFN,
s.setState,
s.getState,
s.addError,
s.mounted
]);
const useAPIQuery: (index: number) => Promise<any> = async (index: number) => {
const colSort = getState('colSort');
const pageSize = getState('pageSize');
const _active_requests = getState('_active_requests');
if (props && props.url) {
const head = new Headers();
head.set('x-limit', String(pageSize ?? 50));
head.set('x-offset', String((pageSize ?? 50) * index));
head.set('x-fieldfilter-tablename', 'scriptcode');
head.set('Authorization', `Token ${props.authtoken}`);
if (colSort?.length && colSort.length > 0) {
head.set(
'x-sort',
colSort
?.map((sort: any) => `${sort.id} ${sort.direction}`)
.reduce((acc: any, val: any) => `${acc},${val}`)
);
}
const currentRequestIndex = _active_requests?.findIndex((f) => f.page === index) ?? -1;
_active_requests?.forEach((r) => {
if ((r.page >= 0 && r.page < index - 2) || (index >= 0 && r.page > index + 2)) {
r.controller?.abort?.();
}
});
if (_active_requests && currentRequestIndex >= 0 && _active_requests[currentRequestIndex]) {
//console.log(`Already queued ${index}`, index, s._active_requests);
return undefined;
}
const controller = new AbortController();
await setStateFN('_active_requests', (cv) => [
...(cv ?? []),
{ controller, page: index }
]);
const res = await fetch(
`${props.url}?x-limit=${String(pageSize ?? 50)}&x-offset=${String((pageSize ?? 50) * index)}`,
{
headers: head,
method: 'GET',
signal: controller?.signal
}
);
if (res.ok) {
const cr = res.headers.get('Content-Range')?.split('/');
if (cr?.[1] && parseInt(cr[1], 10) > 0) {
setState('total_rows', parseInt(cr[1], 10));
}
const data = await res.json();
return data ?? [];
}
addError(`${res.status} ${res.statusText}`, 'api', props.url);
await setStateFN('_active_requests', (cv) => [...(cv ?? []).filter((f) => f.page !== index)]);
}
return [];
};
useEffect(() => {
setState('useAPIQuery', useAPIQuery);
}, [props.url, props.authtoken, mounted]);
return <></>;
});

View File

@ -0,0 +1,163 @@
/* eslint-disable react-refresh/only-export-components */
import { type BaseGridColumn, type GridCell, GridCellKind } from '@glideapps/glide-data-grid';
import { ActionIcon, Select, Stack, TextInput } from '@mantine/core';
import { useDebouncedValue } from '@mantine/hooks';
import { IconX } from '@tabler/icons-react';
import { useEffect, useState } from 'react';
import type { FilterOption, FilterOptionOperator, GridlerStoreState } from './Store';
export type GridCellLoose = {
kind: GridCellKind | string;
} & Omit<GridCell, 'allowOverlay' | 'kind'>;
export interface GridlerColumn extends Partial<BaseGridColumn> {
Cell?: (
row: any,
col: number,
colIndx: string,
value: any,
storeState: GridlerStoreState
) => GridCellLoose;
defaultIcon?: string;
disableFilter?: boolean;
disableMove?: boolean;
disableResize?: boolean;
disableSort?: boolean;
getMenuItems?: (
id: string,
storeState: any,
row?: any,
col?: GridlerColumn,
defaultItems?: Array<any>
) => Array<any>;
id: string;
maxWidth?: number;
minWidth?: number;
width?: number;
}
export const FilterOperators: Array<{ label: string; value: FilterOptionOperator }> = [
{ label: 'Contains', value: 'contains' },
{ label: 'Equal', value: 'eq' },
{ label: 'Not Equal', value: 'neq' },
{ label: 'Greater Than', value: 'gt' },
{ label: 'Greater Than or Equal', value: 'gte' },
{ label: 'Less Than', value: 'lt' },
{ label: 'Less Than or Equal', value: 'lte' },
];
export interface ColumnFilterSetProps {
column: GridlerColumn;
options?: Partial<FilterOption>;
storeState: GridlerStoreState;
}
export type GridlerColumns = Array<GridlerColumn>;
export const ColumnFilterInput = (props: ColumnFilterSetProps) => {
const filterIndex =
props.storeState?.colFilters?.findIndex((f) => f.id === props.column.id) ?? -1;
const filter = props.storeState?.colFilters?.[filterIndex] ?? { id: props.column.id, value: '' };
const [filterValue, setFilterValue] = useState<string>(filter?.value ?? '');
const [defferedFilterValue] = useDebouncedValue(filterValue, 900);
useEffect(() => {
props.storeState.setStateFN('colFilters', (state) => {
const idx = state?.findIndex((f) => f.id === props.column.id) ?? -1;
const filters = state ?? [];
if (idx >= 0) {
filters[idx] = {
...filters[idx],
...props.options,
id: props.column.id,
value: defferedFilterValue,
};
} else {
filters.push({
operator: 'contains',
...props.options,
id: props.column.id,
value: defferedFilterValue,
});
}
return filters;
});
}, [defferedFilterValue]);
return (
<TextInput
onChange={(e) => setFilterValue(e.target.value)}
rightSection={
<ActionIcon color="gray" onClick={() => setFilterValue('')} variant="filled">
<IconX color="red" />
</ActionIcon>
}
value={filterValue ?? filter?.value}
/>
);
};
export const ColumnFilterInputOperator = (props: ColumnFilterSetProps) => {
const filterIndex =
props.storeState?.colFilters?.findIndex((f) => f.id === props.column.id) ?? -1;
const filter = props.storeState?.colFilters?.[filterIndex] ?? {
id: props.column.id,
operator: 'contains',
};
const [filterValue, setFilterValue] = useState<FilterOptionOperator>(
filter?.operator ?? 'contains'
);
const [defferedFilterValue] = useDebouncedValue(filterValue, 900);
useEffect(() => {
props.storeState.setStateFN('colFilters', (state) => {
const idx = state?.findIndex((f) => f.id === props.column.id) ?? -1;
const filters = state ?? [];
if (idx >= 0) {
filters[idx] = {
...filters[idx],
...props.options,
id: props.column.id,
operator: defferedFilterValue,
};
} else {
filters.push({
operator: 'contains',
...props.options,
id: props.column.id,
value: defferedFilterValue,
});
}
return filters;
});
}, [defferedFilterValue]);
return (
<Select
comboboxProps={{ withinPortal: false }}
data={FilterOperators}
maxDropdownHeight={150}
onChange={(value) => setFilterValue(value as any)}
placeholder="Operator"
searchable
value={filterValue ?? filter?.operator}
withScrollArea
/>
);
};
export const ColumnFilterSet = (props: ColumnFilterSetProps) => {
return (
<Stack onClick={(e) => e.stopPropagation()}>
<ColumnFilterInputOperator {...props} />
<ColumnFilterInput {...props} />
</Stack>
);
};

View File

@ -0,0 +1,111 @@
import React, { useEffect, useRef } from 'react';
import { useStore } from './Store';
//The computer component does not need to be recalculated on every render, so we use React.memo to prevent unnecessary re-renders.
export const Computer = React.memo(() => {
const refFirstRun = useRef(0);
const {
_glideref,
colOrder,
colSize,
colSort,
columns,
loadPage,
setState,
setStateFN,
} = useStore((s) => ({
_glideref: s._glideref,
colFilters: s.colFilters,
colOrder: s.colOrder,
colSize: s.colSize,
colSort: s.colSort,
columns: s.columns,
loadPage: s.loadPage,
setState: s.setState,
setStateFN: s.setStateFN,
uniqueid: s.uniqueid,
}));
useEffect(() => {
setState(
'renderColumns',
columns?.map((c) => ({
...c,
hasMenu: c?.hasMenu ?? true,
icon: 'sort',
}))
);
}, [columns]);
useEffect(() => {
if (!colSort) {
return;
}
setStateFN('renderColumns', (cols) => {
return cols?.map((c) => ({
...c,
icon:
c.id && colSort?.find((col) => col.id === c.id)?.direction
? colSort?.find((col) => col.id === c.id)?.direction === 'asc'
? 'sortup'
: 'sortdown'
: (c.defaultIcon ?? 'sort'),
}));
}).then(() => {
loadPage(0, 'all');
});
}, [colSort]);
useEffect(() => {
if (!colSize) {
return;
}
setStateFN('renderColumns', (cols) => {
return cols?.map((c) => ({
...c,
width: c.id && colSize?.[c.id] ? colSize?.[c.id] : c.width,
}));
});
}, [colSize]);
useEffect(() => {
if (!colOrder) {
return;
}
setStateFN('renderColumns', (cols) => {
const result = cols?.sort((a, b) => {
if (colOrder[a.id] > colOrder[b.id]) {
return 1;
}
return -1;
});
return result;
});
}, [colOrder]);
useEffect(() => {
if (!_glideref) {
return;
}
if (refFirstRun.current > 0) {
return;
}
refFirstRun.current = 1;
loadPage(0);
}, [_glideref]);
// console.log('Gridler:Debug:Computer', {
// colFilters,
// colOrder,
// colSize,
// colSort,
// columns,
// uniqueid
// });
return <></>;
});

View File

@ -0,0 +1,62 @@
import React, { useEffect } from 'react';
import { range } from '../utils/range';
import { useStore } from './Store';
//The computer component does not need to be recalculated on every render, so we use React.memo to prevent unnecessary re-renders.
export const Pager = React.memo(() => {
const [
setState,
glideref,
visiblePages,
//_visibleArea,
pageSize,
loadPage,
_loadingList,
hasLocalData
] = useStore((s) => [
s.setState,
s._glideref,
s._visiblePages,
//s._visibleArea,
s.pageSize,
s.loadPage,
s._loadingList,
s.hasLocalData
]);
useEffect(() => {
if (!glideref) {return;}
setState('mounted', true);
}, [setState]);
//Maybe move this into a computer component.
useEffect(() => {
if (!glideref) {return;}
if (hasLocalData) {
//using local data, no need to load pages
return;
}
const firstPage = Math.max(0, Math.floor(visiblePages.y / pageSize));
const lastPage = Math.floor((visiblePages.y + visiblePages.height) / pageSize);
//const upperPage = pageSize * firstPage;
// console.log(
// 'Render1',
// { firstPage, lastPage, upperPage },
// { pageSize, _visibleArea, visiblePages },
// glideref,
// _loadingList,
// _editData
// );
for (const page of range(firstPage, lastPage + 1, 1)) {
loadPage(page);
}
}, [loadPage, pageSize, visiblePages, glideref, _loadingList,hasLocalData]);
return <></>;
});

View File

@ -0,0 +1,643 @@
/* eslint-disable react-refresh/only-export-components */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
type CellArray,
CompactSelection,
type DataEditorRef,
type EditableGridCell,
type GetCellsThunk,
type GridCell,
GridCellKind,
type GridColumn,
type HeaderClickedEventArgs,
type Item,
type Rectangle,
} from '@glideapps/glide-data-grid';
import { getUUID } from '@warkypublic/artemis-kit';
import { getNestedValue } from '@warkypublic/artemis-kit/object';
import { createSyncStore } from '@warkypublic/zustandsyncstore';
import { produce } from 'immer';
import { type PropsWithChildren, useEffect } from 'react';
import { type MantineBetterMenuInstance, useMantineBetterMenus } from '../../MantineBetterMenu';
import { type TRequest } from '../utils/types';
import { ColumnFilterSet, type GridlerColumn, type GridlerColumns } from './Column';
import { SortDownSprite } from './sprites/SortDown';
import { SortUpSprite } from './sprites/SortUp';
import { SpriteImage } from './sprites/SpriteImage';
export type FilterOption = {
datatype?: 'array' | 'boolean' | 'date' | 'function' | 'number' | 'object' | 'string';
id: string;
operator: FilterOptionOperator;
value: string;
value2?: string;
};
export type FilterOptionOperator =
| 'between'
| 'contains'
| 'endswith'
| 'eq'
| 'gt'
| 'gte'
| 'lt'
| 'lte'
| 'neq'
| 'startswith';
export interface GridlerProps extends PropsWithChildren {
columns?: GridlerColumns;
data?: Array<any>;
defaultSort?: Array<SortOption>;
enableOddEvenRowColor?: boolean;
getMenuItems?: (
id: string,
storeState: GridlerState,
row?: any,
col?: GridlerColumn,
defaultItems?: Array<any>
) => Array<any>;
headerHeight?: number;
hideMenu?: (id: string) => void;
maxConcurrency?: number;
pageSize?: number;
progressiveScroll?: boolean;
RenderCell?: <TRowType extends Record<string, string>>(
row: any,
colindex: number,
colid: string,
value: any,
store: GridlerState
) => GridCell;
request?: TRequest;
rowHeight?: number;
showMenu?: (id: string, options?: Partial<MantineBetterMenuInstance>) => void;
uniqueid: string;
}
export interface GridlerState {
_active_requests?: Array<{ controller: AbortController; page: number }>;
_glideref?: DataEditorRef;
_loadingList: CompactSelection;
_page_data: Record<number, Array<any>>;
_scrollTimeout?: any | number;
_visibleArea: Rectangle;
_visiblePages: Rectangle;
addError: (err: string, ...args: Array<any>) => void;
colFilters?: Array<FilterOption>;
colOrder?: Record<string, number>;
colSize?: Record<string, number>;
colSort?: Array<SortOption>;
data?: Array<any>;
errors: Array<string>;
focused?: boolean;
get: () => GridlerState;
getCellContent: (cell: Item) => GridCell;
getCellsForSelection: (
selection: Rectangle,
abortSignal: AbortSignal
) => CellArray | GetCellsThunk;
getState: <K extends keyof GridlerStoreState>(key: K) => GridlerStoreState[K];
hasLocalData: boolean;
loadPage: (page: number, clearMode?: 'all' | 'page') => Promise<void>;
mounted: boolean;
onCellEdited: (cell: Item, newVal: EditableGridCell) => void;
onColumnMoved: (from: number, to: number) => void;
onColumnProposeMove: (startIndex: number, endIndex: number) => boolean;
onColumnResize: (
column: GridColumn,
newSize: number,
colIndex: number,
newSizeWithGrow: number
) => void;
onContextClick: (area: string, event: any, col?: number, row?: number) => void;
onHeaderClicked: (colIndex: number, event: HeaderClickedEventArgs) => void;
onHeaderMenuClick: (col: number, screenPosition: Rectangle) => void;
onVisibleRegionChanged: (
r: Rectangle,
tx: number,
ty: number,
extras: {
freezeRegion?: Rectangle;
freezeRegions?: readonly Rectangle[];
selected?: Item;
}
) => void;
pageSize: number;
reload?: () => Promise<void>;
renderColumns?: GridlerColumns;
setState: <K extends keyof GridlerStoreState>(
key: K,
value: Partial<GridlerStoreState[K]>
) => void;
setStateFN: <K extends keyof GridlerStoreState>(
key: K,
value: (current: GridlerStoreState[K]) => Partial<GridlerStoreState[K]>
) => Promise<void>;
toCell: <TRowType extends Record<string, string>>(row: any, col: number) => GridCell;
total_rows: number;
useAPIQuery?: (index: number) => Promise<Array<Record<string, any>>>;
}
export type GridlerStoreState = GridlerProps & GridlerState;
export type SortOption = { direction: 'asc' | 'desc'; id: string; order?: number };
const { Provider, useStore } = createSyncStore<GridlerStoreState, GridlerProps>(
(set, get) => ({
_loadingList: CompactSelection.empty(),
_page_data: {},
_visibleArea: { height: 10000, width: 1000, x: 0, y: 0 },
_visiblePages: { height: 0, width: 0, x: 0, y: 0 },
addError: (err: string, ...args: Array<any>) => {
const s = get();
console.log('Gridler Error', s.uniqueid, err, args);
set(
produce((state: GridlerStoreState) => {
state.errors = [...state.errors, err];
})
);
},
errors: [],
get: () => get(),
getCellContent: (cell: Item) => {
const state = get();
const [col, row] = cell;
//Handle local data
if (state.data && state.data.length > 0) {
if (state.data[row] === undefined) {
return {
allowOverlay: false,
kind: GridCellKind.Loading,
};
}
return state.toCell(state.data[row], col);
}
//Handle remote paged data
const firstPage = Math.max(0, Math.floor(row / state.pageSize));
const upperPage = state.pageSize * firstPage;
const index = row - upperPage;
const rowData = state._page_data?.[firstPage]?.[index];
//console.log('getCellContent', row, firstPage, upperPage, index, rowData);
//This is empty, that is why the grid renders nothing
if (rowData !== undefined) {
return state.toCell(rowData, col);
}
return {
allowOverlay: false,
kind: GridCellKind.Loading,
};
},
getCellsForSelection: (selection: Rectangle, abortSignal: AbortSignal) => {
return async () => {
const state = get();
//const firstPage = Math.max(0, Math.floor(selection.y / state.pageSize));
//const lastPage = Math.floor((selection.y + selection.height) / state.pageSize);
//console.log('Gridler:Debug:getCellsForSelection', selection, firstPage, lastPage);
await state.setStateFN('_visibleArea', (cv) => {
//if (r.x === cv.x && r.y === cv.y && r.width === cv.width && r.height === cv.height)
// return cv;
return selection;
});
// for (const pageChunk of chunk(
// range(firstPage, lastPage + 1).filter((i) => !state._loadingList.hasIndex(i)),
// state.maxConcurrency
// )) {
// await Promise.all(pageChunk.map(state.loadPage));
// }
// for (const page of range(firstPage - 1, lastPage + 1, 1)) {
// state.loadPage(page);
// }
const result: GridCell[][] = [];
for (let y = selection.y; y < selection.y + selection.height; y++) {
const row: GridCell[] = [];
for (let x = selection.x; x < selection.x + selection.width; x++) {
row.push(state.getCellContent([x, y]));
}
result.push(row);
}
return result as CellArray;
};
},
getState: (key) => {
return get()[key];
},
hasLocalData: false,
loadPage: async (pPage: number, clearMode?: 'all' | 'page') => {
const state = get();
const page = pPage < 0 ? 0 : pPage;
const damageList: { cell: [number, number] }[] = [];
const colLen = Object.keys(state.renderColumns ?? [1, 2, 3]).length;
const upperPage = state.pageSize * page;
const hasPage = state._page_data?.[page]?.length > 0;
//console.log('loadPage', page, clearMode, { upperPage, hasPage, pz: state.pageSize, colLen });
if (clearMode === 'all') {
state._active_requests?.forEach((r) => {
r.controller?.abort?.();
});
state.setState('_page_data', {});
state.setState('_active_requests', []);
state.loadPage(page);
return;
}
if (!state.useAPIQuery) {
console.warn('No useAPIQuery function defined, cannot load page', page);
return;
}
if (!hasPage && clearMode !== 'page') {
state
.useAPIQuery?.(page)
.then((data) => {
state.setStateFN('_page_data', (cv) => {
return { ...cv, [page]: data };
});
for (let row = page; row <= upperPage + state.pageSize; row++) {
for (let col = 0; col <= colLen; col++) {
damageList.push({
cell: [col, row],
});
}
}
state._glideref?.updateCells(damageList);
})
.catch((e) => {
console.warn('loadPage Error: ', page, e);
});
}
},
maxConcurrency: 1,
mounted: false,
onCellEdited: (cell: Item, newVal: EditableGridCell) => {
const state = get();
const [, row] = cell;
//const current = state._editData?.[row];
//if (current === undefined) return;
//todo: complete
},
onColumnMoved: (from: number, to: number) => {
const s = get();
const fromItem = s.renderColumns?.[from];
const toItem = s.renderColumns?.[to];
if (fromItem?.disableMove || toItem?.disableMove) {
return;
}
s.setStateFN('colOrder', (cols) => {
const renderCols = cols ?? s.renderColumns
?.map((col, i) => [col.id, i])
.reduce((acc, [id, i]) => ({ ...acc, [id]: i }), {});;
if (!fromItem?.id || !toItem?.id) {
return renderCols;
}
return { ...renderCols, [fromItem?.id]: to, [toItem?.id]: from };
});
},
onColumnProposeMove: (startIndex: number, endIndex: number) => {
const s = get();
const fromItem = s.renderColumns?.[startIndex];
const toItem = s.renderColumns?.[endIndex];
if (fromItem?.disableMove || toItem?.disableMove) {
return false;
}
return true;
},
onColumnResize: (
column: GridColumn,
newSize: number,
colIndex: number,
newSizeWithGrow: number
) => {
const s = get();
const col = s.renderColumns?.find((col) => col.id === column.id);
if (col?.disableResize) {
return;
}
if (col?.maxWidth && newSize < col?.maxWidth) {
return;
}
if (col) {
s.setStateFN('colSize', (cols) => {
if (cols && col && cols[col.id] === newSize) {
return cols;
}
return { ...cols, [col.id]: newSize };
});
}
},
onContextClick: (area: string, event: any, col?: number, row?: number) => {
const s = get();
const coldef = s.renderColumns?.[col ?? -1];
const items =
area === 'menu'
? [
{
label: `Side menu`,
},
]
: coldef
? [
{
label: `Column ${coldef?.title ?? coldef?.id} Row ${row}`,
},
]
: [
{
label: `No Column ${area}`,
},
];
s.hideMenu?.(area);
s.showMenu?.(area, {
items:
coldef?.getMenuItems?.(
area,
s,
col && row ? s.getCellContent([col, row]) : undefined,
coldef,
items
) ??
s.getMenuItems?.(
area,
s,
col && row ? s.getCellContent([col, row]) : undefined,
coldef,
items
) ??
items,
x: event.clientX ?? event.bounds?.x,
y: event.clientY ?? event.bounds?.y,
});
},
onHeaderClicked: (colIndex: number, event: HeaderClickedEventArgs) => {
const s = get();
event.preventDefault();
const col = s.renderColumns?.[colIndex];
if (!col) {
return;
}
if (!col.disableSort) {
s.setStateFN('colSort', (c) => {
const cols = [...(c ?? [])];
const idx = cols.findIndex((search) => search.id === col.id);
if (idx < 0) {
const newSort: SortOption = { direction: 'asc', id: col.id, order: cols?.length };
cols.push(newSort);
} else if (idx >= 0 && cols[idx].direction === 'asc') {
cols[idx].direction = 'desc';
} else if (idx >= 0 && cols[idx].direction === 'desc') {
cols.splice(idx, 1);
}
return cols;
});
}
},
onHeaderMenuClick: (col: number, screenPosition: Rectangle) => {
const s = get();
const coldef = s.renderColumns?.[col];
if (!coldef) {
return;
}
const items = [
{
label: `Sort ${coldef?.title ?? coldef?.id}`,
},
{
label: 'Sort Ascending',
leftSection: <SpriteImage sprite={SortUpSprite} />,
onClick: () => {
console.log('Sort Ascending');
},
},
{
label: 'Sort Descending',
leftSection: <SpriteImage sprite={SortDownSprite} />,
onClick: () => {
console.log('Sort Descending');
},
},
{
isDivider: true,
},
{
label: `Filter ${coldef?.title ?? coldef?.id}`,
},
{
renderer: <ColumnFilterSet column={coldef} storeState={get()} />,
},
{
isDivider: true,
},
{
label: `Refresh`,
onClickAsync: async () => {
await s.reload?.();
},
},
];
s.hideMenu?.('header-menu');
s.showMenu?.('header-menu', {
items:
coldef?.getMenuItems?.('header-menu', s, undefined, coldef, items) ??
s.getMenuItems?.('header-menu', s, undefined, coldef, items),
x: screenPosition.x,
y: screenPosition.y,
});
},
onVisibleRegionChanged: (
region: Rectangle,
tx: number,
ty: number,
extras: {
freezeRegion?: Rectangle;
freezeRegions?: readonly Rectangle[];
selected?: Item;
}
) => {
const state = get();
if (state._scrollTimeout) {
clearTimeout(state._scrollTimeout);
}
const onVisibleRegionChangedDebounced = () => {
//console.log('Gridler:Debug:VisibleRegionChanged', r);
const state = get();
const firstPage = Math.max(0, Math.floor(region.y / state.pageSize));
const lastPage = Math.floor((region.y + region.height) / state.pageSize);
const upperPage = state.pageSize * firstPage;
const previousPage = Math.max(0, Math.floor(state._visiblePages.y / state.pageSize));
const pageDif = firstPage - previousPage;
// console.log(
// 'Page dif',
// pageDif,
// { previousPage, firstPage, lastPage, onder: pageDif - 1 === lastPage },
// region
// );
// if (pageDif - 1 === lastPage) {
// console.log('Is onder', lastPage, pageDif);
// }
if (state.progressiveScroll && pageDif > 1) {
const state = get();
const newpos = (previousPage + 2) * state.pageSize * (state.rowHeight ?? 22);
// console.log('Pending scroll exec', newpos, {
// pageSize: state.pageSize,
// rowHeight: state.rowHeight
// });
state._glideref?.scrollTo(
0,
{
amount: newpos,
unit: 'px',
},
'vertical'
);
return;
}
//console.log('VIsi change', { firstPage, lastPage }, state?._page_data[lastPage]);
// if (state._active_requests && state._active_requests.filter((f)=>f.page > firstPage - 1)) {
// }
//console.log('Gridler:Debug:VisibleRegionChanged', region, firstPage, lastPage);
state.setState('_visiblePages', region);
};
state.setState(
'_scrollTimeout',
setTimeout(() => {
onVisibleRegionChangedDebounced();
}, 100)
);
},
pageSize: 50,
setState: (key, value) => {
set(
produce((state) => {
state[key] = value;
})
);
},
setStateFN: (key, value) => {
const p = new Promise<void>((resolve, reject) => {
set(
produce((state) => {
if (typeof value === 'function') {
state[key] = (value as (value: any) => any)(state[key]);
} else {
reject(new Error(`Not a function ${value}`));
throw Error(`Not a function ${value}`);
}
})
);
resolve();
});
return p;
},
toCell: <T extends Record<string, string>>(row: T, col: number): GridCell => {
const s = get();
const columns = s.renderColumns;
const coldef: GridlerColumn | undefined = columns?.[col];
const ref: string = coldef?.id ?? coldef?.title ?? String(col);
if (ref === undefined || ref === null || row === undefined || row === null) {
if (coldef?.Cell) {
return coldef?.Cell(row, col, ref, undefined, s) as GridCell;
}
if (s.RenderCell) {
return s.RenderCell(row, col, ref, undefined, s);
}
return {
allowOverlay: false,
kind: GridCellKind.Loading,
};
}
try {
const val = String(ref).includes('.') ? (getNestedValue(ref, row) ?? '') : row?.[ref];
if (coldef?.Cell) {
return coldef?.Cell(row, col, ref, val, s) as GridCell;
}
if (s.RenderCell) {
return s.RenderCell(row, col, ref, val, s);
}
return {
allowOverlay: true,
data: val,
displayData: String(val),
kind: GridCellKind.Text,
};
} catch (e) {
if (s.RenderCell) {
return s.RenderCell(row, col, ref, row?.[ref ?? ''], s);
}
return {
allowOverlay: false,
kind: GridCellKind.Loading,
skeletonWidthVariability: 50,
};
}
},
total_rows: 1000,
uniqueid: getUUID(),
}),
(props) => {
const [setState, glideref, getState] = props.useStore((s) => [
s.setState,
s._glideref,
s.getState,
]);
const menus = useMantineBetterMenus();
useEffect(() => {
setState('mounted', true);
}, [setState]);
return {
...props,
hasLocalData: props.data && props.data.length > 0,
hideMenu: props.hideMenu ?? menus.hide,
showMenu: props.showMenu ?? menus.show,
total_rows: props.data?.length ?? getState('total_rows'),
};
}
);
export type useStoreReturnType = ReturnType<typeof useStore>;
export { Provider, useStore };

View File

@ -0,0 +1,13 @@
import { Sprite, SpriteProps } from '@glideapps/glide-data-grid';
export const SortSprite: Sprite = (props: Partial<SpriteProps>) => {
const fg = props.fgColor ?? 'currentColor';
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="none">
<path
fill="${fg}"
d="M2.22 9.967L7.97 4.22l.085-.074l.058-.038l.072-.039l.105-.04l.105-.022l.052-.005L8.5 4l.057.002l.092.013l.107.03l.085.037l.054.03l.063.044l.072.064l5.75 5.747a.75.75 0 0 1-.976 1.133l-.084-.072L9.25 6.56v16.69a.75.75 0 0 1-1.493.102l-.007-.102V6.56l-4.47 4.468a.75.75 0 0 1-.976.072l-.084-.072a.75.75 0 0 1-.073-.977zM19.5 4a.75.75 0 0 1 .743.648l.007.102v16.687l4.47-4.467l.084-.073a.75.75 0 0 1 1.049 1.05l-.073.083l-5.728 5.727a.75.75 0 0 1-1.031.07l-.073-.07l-5.728-5.727l-.073-.084a.75.75 0 0 1-.007-.882l.08-.094l.084-.073a.75.75 0 0 1 .882-.007l.094.08l4.47 4.469V4.75l.007-.102A.75.75 0 0 1 19.5 4"
></path>
</svg>`;
};

View File

@ -0,0 +1,12 @@
import { Sprite, SpriteProps } from '@glideapps/glide-data-grid';
export const SortDownSprite: Sprite = (props: Partial<SpriteProps>) => {
const fg = props.fgColor ?? 'currentColor';
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="none">
<path
fill="${fg}"
d="M15 2.5a.5.5 0 0 0-1 0v13.793l-2.146-2.147a.5.5 0 0 0-.708.708l3 3a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L15 16.293zM2.5 4a.5.5 0 0 0 0 1h9a.5.5 0 0 0 0-1zM5 7.5a.5.5 0 0 1 .5-.5h6a.5.5 0 0 1 0 1h-6a.5.5 0 0 1-.5-.5M8.5 10a.5.5 0 0 0 0 1h3a.5.5 0 0 0 0-1z"
></path>
</svg>
`;
};

View File

@ -0,0 +1,12 @@
import { Sprite, SpriteProps } from '@glideapps/glide-data-grid';
export const SortUpSprite: Sprite = (props: Partial<SpriteProps>) => {
const fg = props.fgColor ?? 'currentColor';
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" fill="none">
<path
fill="${fg}"
d="M15 17.5a.5.5 0 0 1-1 0V3.707l-2.146 2.147a.5.5 0 0 1-.708-.708l3-3a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L15 3.707zM2.5 16a.5.5 0 0 1 0-1h9a.5.5 0 0 1 0 1zM5 12.5a.5.5 0 0 0 .5.5h6a.5.5 0 0 0 0-1h-6a.5.5 0 0 0-.5.5M8.5 10a.5.5 0 0 1 0-1h3a.5.5 0 0 1 0 1z"
></path>
</svg>
`;
};

View File

@ -0,0 +1,7 @@
import { Sprite, SpriteProps } from '@glideapps/glide-data-grid';
export const SpriteImage = (props: { alt?:string; sprite: Sprite, } & Partial<SpriteProps>) => {
return (
<img alt={props.alt ?? "Sprite Image"} src={`data:image/svg+xml;utf8,${props.sprite({ ...props, sprite: undefined } as any)}`} />
);
};

View File

@ -0,0 +1,117 @@
import type { GetRowThemeCallback } from '@glideapps/glide-data-grid';
import { darken, lighten, useMantineColorScheme, useMantineTheme } from '@mantine/core';
import { useEffect, useState } from 'react';
import { useStore } from '../components/Store';
export const offsetRows = (colorScheme: any) => (i: number) =>
i % 2 === 0
? undefined
: {
bgCell: colorScheme === 'dark' ? '#303030' : '#e1effc'
};
export const useGridTheme = () => {
const theme = useMantineTheme();
const { colorScheme } = useMantineColorScheme();
const { enableOddEvenRowColor, focused } = useStore((state) => ({
enableOddEvenRowColor: state.enableOddEvenRowColor,
focused: state.focused
}));
const cellColor = {
auto: focused ? lighten(theme.colors.blue[4], 0.9) : '#ffffff',
dark: focused ? darken('#bacfe0', 0.2) : theme.colors.dark[7],
light: focused ? lighten(theme.colors.blue[4], 0.8) : '#ffffff'
}[colorScheme];
// if (noFocusHighlight) {
// cellColor = {
// dark: theme.colors.dark[8],
// light: '#ffffff'
// }[colorScheme];
// }
const gridThemeDark = {
accentColor: 'none',
accentLight: '#2824ab3c',
baseFontStyle: '13px',
bgBubble: '#212121',
bgBubbleSelected: '#000000',
bgCell: cellColor,
bgCellMedium: '#202027',
bgHeader: '#2A2A2A',
bgHeaderHasFocus: '#181818',
bgHeaderHovered: '#404040',
bgIconHeader: '#b8b8b8',
bgSearchResult: '#423c24',
borderColor: '#eee1',
drilldownBorder: 'rgba(225,225,225,0.4)',
fgIconHeader: '#000000',
fontFamily:
'Inter, Roboto, -apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Ubuntu, noto, arial, sans-serif',
headerFontStyle: '500 13px',
linkColor: '#4F5DFF',
textBubble: '#ffffff',
textDark: '#dedede',
textGroupHeader: '#dedede',
textHeader: '#a1a1a1',
textHeaderSelected: '#000000',
textLight: '#a0a0a0',
textMedium: '#b8b8b8'
};
const gridThemeLight = {
bgCell: cellColor,
textGroupHeader: '#2c5491'
};
const commonTheme = colorScheme === 'dark' ? gridThemeDark : gridThemeLight;
const [gridTheme, setGridTheme] = useState(commonTheme);
useEffect(() => {
setGridTheme(commonTheme);
}, [colorScheme, focused]);
const getRowThemeOverride: GetRowThemeCallback = (row) => {
// const rowColor: any = {
// auto: {
// bgCell: '#d9e8ff',
// bgCellMedium: '#d9e8ff'
// },
// dark: {
// bgCell: '#1864ab3c',
// bgCellMedium: '#1864ab3c'
// },
// light: {
// bgCell: '#d9e8ff',
// bgCellMedium: '#d9e8ff'
// }
// }[colorScheme];
// for (const selectedRow of gridSelection?.rows) {
// if (selectedRow === row) {
// return {
// bgCell: rowColor.bgCell,
// bgCellMedium: rowColor.bgCellMedium
// };
// }
// }
return enableOddEvenRowColor ? offsetRows(colorScheme)(row) : undefined;
};
return { getRowThemeOverride, gridTheme };
};

View File

@ -0,0 +1,79 @@
import { Divider, Stack, TextInput } from '@mantine/core';
import { useLocalStorage } from '@mantine/hooks';
import type { GridlerColumns } from '../components/Column';
import { APIAdaptorGoLangv2 } from '../components/APIAdaptorGoLangv2';
import { Gridler } from '../Gridler';
export const GridlerGoAPIExampleEventlog = () => {
const [apiUrl, setApiUrl] = useLocalStorage({
defaultValue: 'http://localhost:8080/api',
key: 'apiurl',
});
const [apiKey, setApiKey] = useLocalStorage({ defaultValue: '', key: 'apikey' });
const columns: GridlerColumns = [
{
id: 'rid_atevent',
title: 'RID',
width: 100,
},
{
Cell: (_row, _col, _colindex, value) => {
return {
cursor: 'crosshair',
data: value,
displayData: `- ${value}`,
kind: 'text',
};
},
grow: 1,
id: 'changedate',
title: 'Date',
width: 200,
},
{
id: 'changetime',
title: 'Time',
width: 200,
},
{
id: 'changeuser',
title: 'User',
},
{
id: 'actionx',
title: 'Action',
width: 100,
},
];
return (
<Stack h="80vh">
<h2>Demo Using Go API Adaptor</h2>
<TextInput label="API Url" onChange={(e) => setApiUrl(e.target.value)} value={apiUrl} />
<TextInput label="API Key" onChange={(e) => setApiKey(e.target.value)} value={apiKey} />
<Divider />
<Gridler
columns={columns}
getMenuItems={(id, _state, row, col, defaultItems) => {
return [
...(defaultItems ?? []),
{
id: 'test',
label: `Test ${id}`,
onClick: () => {
console.log('Test clicked', row, col);
},
},
];
}}
uniqueid="gridtest"
>
<APIAdaptorGoLangv2 authtoken={apiKey} url={`${apiUrl}/core/atevent`} />
</Gridler>
</Stack>
);
};

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,37 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Box } from '@mantine/core';
import { fn } from 'storybook/test';
import { GridlerGoAPIExampleEventlog } from './Examples.goapi';
const Renderable = (props: any) => {
return <Box h="100%" mih="400px" miw="400px" w='100%' > <GridlerGoAPIExampleEventlog {...props} /></Box>;
};
const meta = {
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
component: Renderable,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
title: 'Grid/Gridler API',
} satisfies Meta<typeof Renderable>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const BasicExample: Story = {
args: {
label: 'Test',
},
};

View File

@ -0,0 +1,37 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Box } from '@mantine/core';
import { fn } from 'storybook/test';
import { GridlerLocaldataExampleEventlog } from './Examples.localdata';
const Renderable = (props: any) => {
return <Box h="100%" mih="400px" miw="400px" w='100%' > <GridlerLocaldataExampleEventlog {...props} /></Box>;
};
const meta = {
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
component: Renderable,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
title: 'Grid/Gridler Local',
} satisfies Meta<typeof Renderable>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const BasicExample: Story = {
args: {
label: 'Test',
},
};

View File

@ -0,0 +1,81 @@
export type APIOptionsType = {
autocreate?: boolean
autoref?: boolean
baseurl?: string
getAPIProvider?: () => { provider: string; providerKey: string }
getAuthToken?: () => string
operations?: Array<FetchAPIOperation>
postfix?: string
prefix?: string
requestTimeoutSec?: number
}
export interface APIResponse {
errmsg: string
payload?: any
retval: number
}
export interface FetchAPIOperation {
name?: string
op?: string
type: FetchOpTypes //x-fieldfilter
value: string
}
export type FetchOpTypes = GoAPIEnum & string
/**
* @description Types for the Go Rest API headers
* @typedef {String} GoAPIEnum
*/
export type GoAPIEnum = 'advsql'
| 'api-key'
| 'api-range-from'
| 'api-range-size'
| 'api-range-total'
| 'api-src'
| 'api'
| 'association_autocreate'
| 'association_autoupdate'
| 'association-update'
| 'cql-sel'
| 'custom-sql-join'
| 'custom-sql-or'
| 'custom-sql-w'
| 'detailapi'
| 'distinct'
| 'expand'
| 'fetch-rownumber'
| 'fieldfilter'
| 'fieldfilter'
| 'func'
| 'limit'
| 'no-return'
| 'not-select-fields'
| 'offset'
| 'parm'
| 'pkrow'
| 'preload'
| 'searchfilter'
| 'searchfilter'
| 'searchop'
| 'searchop'
| 'select-fields'
| 'simpleapi'
| 'skipcache'
| 'skipcount'
| 'sort'
export type GoAPIHeaderKeys = `x-${GoAPIEnum}`
export type MetaCallback = (data: MetaData) => void
export interface MetaData {
limit?: number
offset?: number
total?: number
}

View File

View File

@ -0,0 +1,37 @@
function range(end: number): number[];
function range(start: number, end: number): number[];
function range(start: number, end: number, step: number): number[];
function range(startOrEnd: number, end?: number, step: number = 1): number[] {
let start: number;
// Handle single argument case: range(4) -> [0, 1, 2, 3]
if (end === undefined) {
start = 0;
end = startOrEnd;
} else {
start = startOrEnd;
}
// Validate step
if (step === 0) {
throw new Error('Step cannot be zero');
}
const result: number[] = [];
if (step > 0) {
for (let i = start; i < end; i += step) {
result.push(i);
}
} else {
for (let i = start; i > end; i += step) {
result.push(i);
}
}
return result;
}
export { range };

View File

@ -0,0 +1,18 @@
export type APIType = 'gorest' |'gorest2'| 'resolvespec';
export const APITypes: Record<string, APIType> = {
GoRest: 'gorest',
GoRest2: 'gorest2',
ResolveSpec: 'resolvespec'
} as const;
export interface APIOptions {
authtoken?: string;
primaryKey?: string;
schemaName?: string;
tableName?: string;
type?: APIType;
url?: string;
}
export type TRequest = 'change' | 'delete' | 'insert' | 'select' ;

View File

@ -0,0 +1,2 @@
import { type MenuStoreProps } from './Store';
export declare function MantineBetterMenusProvider(props: React.PropsWithChildren<MenuStoreProps>): import("react/jsx-runtime").JSX.Element;

View File

@ -0,0 +1,51 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { Button } from '@mantine/core';
import { fn } from 'storybook/test';
import { MantineBetterMenusProvider, useMantineBetterMenus } from './';
const Renderable = (props: Record<string,unknown>) => {
return (
<MantineBetterMenusProvider providerID='test' {...props} >
<Menu/>
</MantineBetterMenusProvider>
);
}
const Menu = () => {
const menus = useMantineBetterMenus();
//menus.setState("menus",[{id:"test",items:[{id:"1",label:"Test",onClick:()=>{console.log("Clicked")}}]}])
return <Button onClick={()=> menus.show("test",{})}>Menu</Button>;
}
const meta = {
// Use `fn` to spy on the onClick arg, which will appear in the actions panel once invoked: https://storybook.js.org/docs/essentials/actions#action-args
args: { onClick: fn() },
// More on argTypes: https://storybook.js.org/docs/api/argtypes
argTypes: {
backgroundColor: { control: 'color' },
},
component: Renderable,
parameters: {
// Optional parameter to center the component in the Canvas. More info: https://storybook.js.org/docs/configure/story-layout
layout: 'centered',
},
// This component will have an automatically generated Autodocs entry: https://storybook.js.org/docs/writing-docs/autodocs
tags: ['autodocs'],
title: 'UI/Mantine Better Menu',
} satisfies Meta<typeof Renderable>;
export default meta;
type Story = StoryObj<typeof meta>;
// More on writing stories with args: https://storybook.js.org/docs/writing-stories/args
export const BasicExample: Story = {
args: {
label: 'Test',
},
};

View File

@ -0,0 +1,11 @@
import { MenuRenderer } from './MenuRenderer';
import { MantineBetterMenusStoreProvider, type MenuStoreProps } from './Store';
export function MantineBetterMenusProvider(props: React.PropsWithChildren<MenuStoreProps>) {
return (
<MantineBetterMenusStoreProvider {...props}>
<MenuRenderer />
{props.children}
</MantineBetterMenusStoreProvider>
);
}

View File

@ -0,0 +1 @@
export declare function MenuRenderer(): import("react/jsx-runtime").JSX.Element;

View File

@ -0,0 +1,90 @@
import { Menu, Portal } from '@mantine/core';
import React, { useState } from 'react';
import { type MantineBetterMenuInstanceItem, useMantineBetterMenus } from './Store';
export function MenuRenderer() {
const { menus, providerID, setInstanceState } = useMantineBetterMenus((s) => ({
menus: s.menus,
providerID: s.providerID,
setInstanceState: s.setInstanceState,
setState: s.setState
}));
return (
<Portal id={`bmm_portal_${providerID}`} key={`bmm_portal_${providerID}`}>
{React.Children.toArray(
menus?.map((m, menuIndex) => {
return (
<Menu
shadow="md"
width={200}
{...m.menuProps}
key={`bmm_menu_${providerID}_${menuIndex}`}
onClose={() => {
setInstanceState(m.id, 'visible', false);
m.menuProps?.onClose?.();
}}
opened={m.visible}
>
<Menu.Target>
<div
id={`bmm_${providerID}_${menuIndex}_target`}
style={{ left: m.x, position: 'fixed', top: m.y, visibility: 'hidden' }}
/>
</Menu.Target>
<Menu.Dropdown>
{m.renderer
? m.renderer
: React.Children.toArray(
m.items?.map((item, itemIndex) => (
<MenuItemRenderer
key={`bmm_${providerID}_${menuIndex}_item${itemIndex}`}
{...item}
/>
))
)}
</Menu.Dropdown>
</Menu>
);
})
)}
</Portal>
);
}
const MenuItemRenderer = ({ children, label, ...props }: MantineBetterMenuInstanceItem) => {
const [loading, setLoading] = useState<boolean>(false);
if (typeof props.renderer === 'function') {
return props.renderer({ ...props, loading, renderer: undefined, setLoading });
}
if (typeof props.renderer === 'object') {
return props.renderer;
}
if (props.isDivider) {
return <Menu.Divider />;
}
if (!props.onClick && !props.onClickAsync) {
return <Menu.Label {...(props as Record<string,unknown>)}> {children ?? label}</Menu.Label>;
}
return (
<Menu.Item
{...props}
disabled={loading}
onClick={(e) => {
props.onClick?.(e );
if (props.onClickAsync) {
setLoading(true);
props.onClickAsync().finally(() => setLoading(false));
}
}}
>
{children ?? label}
</Menu.Item>
);
};

43
src/MantineBetterMenu/Store.d.ts vendored Normal file
View File

@ -0,0 +1,43 @@
import { type MenuItemProps, type MenuProps } from '@mantine/core';
import { type ReactNode } from 'react';
export interface MantineBetterMenuInstance {
id: string;
items?: Array<MantineBetterMenuInstanceItem>;
menuProps?: MenuProps;
renderer?: ReactNode;
visible: boolean;
x: number;
y: number;
}
export interface MantineBetterMenuInstanceItem extends Partial<MenuItemProps> {
isDivider?: boolean;
label?: string;
onClick?: (e?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
onClickAsync?: () => Promise<void>;
renderer?: ((props: MantineBetterMenuInstanceItem & Record<string, unknown>) => ReactNode) | ReactNode;
}
export interface MenuStoreProps {
providerID?: string;
}
export type MenuStoreState = MenuStoreProps & MenuStoreStateOnly;
export interface MenuStoreStateOnly {
hide: (id: string) => void;
menus: Array<MantineBetterMenuInstance>;
setInstanceState: <K extends keyof MantineBetterMenuInstance>(instanceID: string, key: K, value: MantineBetterMenuInstance[K]) => void;
setState: <K extends keyof MenuStoreState>(key: K, value: Partial<MenuStoreState[K]>) => void;
show: (id: string, options?: Partial<MantineBetterMenuInstance>) => void;
}
declare const MantineBetterMenusStoreProvider: (props: {
children: ReactNode;
} & {
firstSyncProps?: string[];
persist?: import("zustand/middleware").PersistOptions<Partial<MenuStoreProps & MenuStoreStateOnly>, Partial<MenuStoreProps & MenuStoreStateOnly>, unknown> | undefined;
} & MenuStoreProps) => React.ReactNode, useMantineBetterMenus: {
(): {
$sync?: ((props: MenuStoreProps) => void) | undefined;
} & MenuStoreProps & MenuStoreStateOnly;
<U>(selector: (state: {
$sync?: ((props: MenuStoreProps) => void) | undefined;
} & MenuStoreProps & MenuStoreStateOnly) => U, equalityFn?: ((a: U, b: U) => boolean) | undefined): U;
};
export { MantineBetterMenusStoreProvider, useMantineBetterMenus };

View File

@ -0,0 +1,104 @@
/* eslint-disable react-refresh/only-export-components */
import { type MenuItemProps, type MenuProps } from '@mantine/core';
import { getUUID } from '@warkypublic/artemis-kit';
import { createSyncStore } from '@warkypublic/zustandsyncstore';
import { produce } from 'immer';
import { type ReactNode } from 'react';
export interface MantineBetterMenuInstance {
id: string;
items?: Array<MantineBetterMenuInstanceItem>;
menuProps?: MenuProps;
renderer?: ReactNode;
visible: boolean;
x: number;
y: number;
}
export interface MantineBetterMenuInstanceItem extends Partial<MenuItemProps> {
isDivider?: boolean;
label?: string;
onClick?: (e?: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
onClickAsync?: () => Promise<void>;
renderer?:
| ((props: MantineBetterMenuInstanceItem & Record<string, unknown>) => ReactNode)
| ReactNode;
}
export interface MenuStoreProps {
menus?: Array<MantineBetterMenuInstance>;
providerID?: string;
}
export type MenuStoreState = MenuStoreProps & MenuStoreStateOnly;
export interface MenuStoreStateOnly {
hide: (id: string) => void;
menus: Array<MantineBetterMenuInstance>;
setInstanceState: <K extends keyof MantineBetterMenuInstance>(
instanceID: string,
key: K,
value: MantineBetterMenuInstance[K]
) => void;
setState: <K extends keyof MenuStoreState>(key: K, value: Partial<MenuStoreState[K]>) => void;
show: (id: string, options?: Partial<MantineBetterMenuInstance>) => void;
}
const { Provider:MantineBetterMenusStoreProvider, useStore:useMantineBetterMenus } = createSyncStore<MenuStoreState, MenuStoreProps>(
(set, get) => ({
hide: (id: string) => {
const s = get();
s.setInstanceState(id, 'visible', false);
},
menus: [],
setInstanceState: (id, key, value) => {
//@ts-expect-error Type instantiation is excessively deep and possibly infinite.
set(
produce((state: MenuStoreState) => {
const idx = state?.menus?.findIndex((m: MantineBetterMenuInstance) => m.id === id);
if (idx >= 0) {
state.menus[idx][key] = value;
}
})
);
},
setState: (key, value) => {
set(
produce((state) => {
state[key] = value;
})
);
},
show: (id: string, options?: Partial<Omit<MantineBetterMenuInstance, 'id'>>) => {
const s = get();
const menuIndex = s.menus.findIndex((m) => m.id === id);
const menu: Partial<MantineBetterMenuInstance> = s.menus[menuIndex]
? { ...s.menus[menuIndex] }
: {};
Object.assign(menu, options);
menu.id = menu.id ?? id;
menu.visible = !(menu.visible ?? false);
if (menuIndex < 0) {
s.setState('menus', [...s.menus, menu as MantineBetterMenuInstance]);
} else {
set(
produce((state: MenuStoreState) => {
if (!state.menus) {
state.menus = [];
}
state.menus[menuIndex] = { ...state.menus[menuIndex], ...menu };
})
);
}
}
}),
(props) => {
return {
providerID: props.providerID ?? `MenuStore-${getUUID()}`
};
}
);
export { MantineBetterMenusStoreProvider,useMantineBetterMenus };

3
src/MantineBetterMenu/index.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
export { MantineBetterMenusProvider } from './MantineBetterMenu';
export { useMantineBetterMenus } from './Store';
export type { MantineBetterMenuInstance, MantineBetterMenuInstanceItem, MenuStoreState } from './Store';

View File

@ -0,0 +1,7 @@
export { MantineBetterMenusProvider } from './MantineBetterMenu';
export { useMantineBetterMenus } from './Store';
export type {
MantineBetterMenuInstance,
MantineBetterMenuInstanceItem,
MenuStoreState
} from './Store';

1
src/globals.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module '*.css';

1
src/lib.d.ts vendored Normal file
View File

@ -0,0 +1 @@
export { type MantineBetterMenuInstance, type MantineBetterMenuInstanceItem, MantineBetterMenusProvider, type MenuStoreState, useMantineBetterMenus, } from "./MantineBetterMenu";

7
src/lib.ts Normal file
View File

@ -0,0 +1,7 @@
export {
type MantineBetterMenuInstance,
type MantineBetterMenuInstanceItem,
MantineBetterMenusProvider,
type MenuStoreState,
useMantineBetterMenus,
} from "./MantineBetterMenu";

28
tsconfig.app.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"declaration": true,
"emitDeclarationOnly": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
tsconfig.json Normal file
View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

25
tsconfig.node.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

36
vite.config.ts Normal file
View File

@ -0,0 +1,36 @@
import { defineConfig } from "vite";
import { dirname } from "node:path";
import * as path from "path";
import { fileURLToPath } from "node:url";
import react from "@vitejs/plugin-react-swc";
import { peerDependencies } from "./package.json";
import dts from "vite-plugin-dts";
const __dirname = dirname(fileURLToPath(import.meta.url));
// https://vite.dev/config/
export default defineConfig({
plugins: [
dts({
outDir: "dist",
entryRoot: "src",
staticImport: true,
}),
react(),
],
build: {
sourcemap: true,
lib: {
entry: path.resolve(__dirname, "src/lib.ts"),
name: "lib",
formats: ["es", "cjs"],
fileName: (format) => `lib.${format}.js`,
},
emptyOutDir: true,
rollupOptions: {
external: Object.keys(peerDependencies),
},
},
});