@typix-editor/extension-max-length 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Diyorbek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
File without changes
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ 'use client'
2
+ var w=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var A=(t,n)=>{for(var a in n)w(t,a,{get:n[a],enumerable:!0})},G=(t,n,a,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let c of B(n))!z.call(t,c)&&c!==a&&w(t,c,{get:()=>n[c],enumerable:!(s=W(n,c))||s.enumerable});return t};var J=t=>G(w({},"__esModule",{value:!0}),t);var U={};A(U,{MaxLengthExtension:()=>M});module.exports=J(U);var $=require("@lexical/react/LexicalComposerContext"),T=require("@lexical/selection"),N=require("@lexical/utils"),g=require("lexical"),u=require("react");function I(t,n,a){switch(a||(t=t.replace(/\s/g,"")),n){case"words":return t.trim().split(/\s+/).filter(s=>s.length>0).length;case"bytes":return new Blob([t]).size;default:if(typeof Intl<"u"&&"Segmenter"in Intl)try{return[...new Intl.Segmenter().segment(t)].length}catch{console.warn("Intl.Segmenter not available, using fallback")}return O(t)}}function O(t){let n=t.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDFFF]/g);return n?n.length:0}function M({maxLength:t,mode:n="characters",onLimitReached:a,onChange:s,warningThreshold:c=.9,onWarning:f,strategy:h="prevent",countWhitespace:d=!0,customCounter:b,debug:L=!1}){let[m]=(0,$.useLexicalComposerContext)(),C=(0,u.useRef)(null),p=(0,u.useRef)(!1),F=(0,u.useRef)({maxLength:t,mode:n,onLimitReached:a,onChange:s,warningThreshold:c,onWarning:f,strategy:h,countWhitespace:d,customCounter:b,debug:L});(0,u.useEffect)(()=>{F.current={maxLength:t,mode:n,onLimitReached:a,onChange:s,warningThreshold:c,onWarning:f,strategy:h,countWhitespace:d,customCounter:b,debug:L}},[t,n,a,s,c,f,h,d,b,L]);let i=(0,u.useCallback)((...E)=>{F.current.debug&&console.log("[MaxLength]",...E)},[]);return(0,u.useEffect)(()=>{i("Registering max length extension",{maxLength:t,mode:n,strategy:h});let E=m.registerNodeTransform(g.RootNode,l=>{let y=(0,g.$getSelection)();if(!(0,g.$isRangeSelection)(y)||!y.isCollapsed())return;let e=F.current,x=m.getEditorState(),R=l.getTextContent(),r=e.customCounter?e.customCounter(R):I(R,e.mode,e.countWhitespace),D=x.read(()=>l.getTextContent()),S=e.customCounter?e.customCounter(D):I(D,e.mode,e.countWhitespace);if(i("Content length",{current:r,previous:S,max:e.maxLength}),r!==S&&e.onChange){let o=e.maxLength-r;e.onChange(r,e.maxLength,o)}let v=Math.floor(e.maxLength*e.warningThreshold);if(r>=v&&r<e.maxLength&&!p.current&&e.onWarning){p.current=!0;let o=e.maxLength-r;i("Warning threshold reached",{currentLength:r,warningLimit:v}),e.onWarning(r,e.maxLength,o)}if(r<v&&(p.current=!1),r>e.maxLength){let o=r-e.maxLength;i("Limit exceeded",{exceeded:o,strategy:e.strategy}),e.onLimitReached&&e.onLimitReached(r,e.maxLength,o);let k=y.anchor;switch(e.strategy){case"prevent":S===e.maxLength&&C.current!==x?(i("Restoring previous state"),C.current=x,(0,N.$restoreEditorState)(m,x)):(i("Trimming from cursor",{amount:o}),(0,T.$trimTextContentFromAnchor)(m,k,o));break;case"trim":i("Trimming from cursor",{amount:o}),(0,T.$trimTextContentFromAnchor)(m,k,o);break;case"truncate":i("Truncating from end",{amount:o}),m.update(()=>{let P=R.slice(0,e.maxLength);l.clear(),l.append(m.parseEditorState(JSON.stringify({root:{children:[{type:"paragraph",children:[{type:"text",text:P}]}]}})).read(()=>l))});break}}});return()=>{i("Unregistering max length extension"),E(),C.current=null,p.current=!1}},[m,i]),null}M.displayName="Typix.MaxLengthExtension";0&&(module.exports={MaxLengthExtension});
@@ -0,0 +1,127 @@
1
+ interface MaxLengthExtensionProps {
2
+ /**
3
+ * Maximum character limit
4
+ * @example 280 // Twitter-style limit
5
+ * @example 5000 // Long-form content
6
+ */
7
+ maxLength: number;
8
+ /**
9
+ * Character counting mode
10
+ * @default 'characters'
11
+ */
12
+ mode?: 'characters' | 'words' | 'bytes';
13
+ /**
14
+ * Callback when limit is reached
15
+ * @param current - Current character count
16
+ * @param max - Maximum allowed
17
+ * @param exceeded - Amount exceeded (if any)
18
+ */
19
+ onLimitReached?: (current: number, max: number, exceeded: number) => void;
20
+ /**
21
+ * Callback on every character change
22
+ * @param current - Current character count
23
+ * @param max - Maximum allowed
24
+ * @param remaining - Characters remaining
25
+ */
26
+ onChange?: (current: number, max: number, remaining: number) => void;
27
+ /**
28
+ * Whether to show a warning before hitting the limit
29
+ * @default 0.9 (90%)
30
+ */
31
+ warningThreshold?: number;
32
+ /**
33
+ * Callback when warning threshold is reached
34
+ */
35
+ onWarning?: (current: number, max: number, remaining: number) => void;
36
+ /**
37
+ * Strategy when limit is exceeded
38
+ * @default 'prevent' - Prevents further input
39
+ * @alternative 'trim' - Trims oldest content
40
+ * @alternative 'truncate' - Truncates from cursor position
41
+ */
42
+ strategy?: 'prevent' | 'trim' | 'truncate';
43
+ /**
44
+ * Whether to count whitespace
45
+ * @default true
46
+ */
47
+ countWhitespace?: boolean;
48
+ /**
49
+ * Custom character counter function
50
+ * Useful for emoji, unicode, or special counting rules
51
+ */
52
+ customCounter?: (text: string) => number;
53
+ /**
54
+ * Enable debug logging
55
+ * @default false
56
+ */
57
+ debug?: boolean;
58
+ }
59
+ /**
60
+ * MaxLengthExtension
61
+ *
62
+ * Enforces character/word limits in Lexical editor with flexible strategies
63
+ * and callbacks for UI feedback.
64
+ *
65
+ * Features:
66
+ * - Multiple counting modes (characters, words, bytes)
67
+ * - Configurable strategies (prevent, trim, truncate)
68
+ * - Warning thresholds
69
+ * - Custom counter support
70
+ * - Proper emoji/unicode handling
71
+ * - Memory-efficient with cleanup
72
+ *
73
+ * @example
74
+ * Basic usage:
75
+ * ```tsx
76
+ * <LexicalComposer>
77
+ * <MaxLengthExtension maxLength={280} />
78
+ * </LexicalComposer>
79
+ * ```
80
+ *
81
+ * @example
82
+ * With callbacks:
83
+ * ```tsx
84
+ * <MaxLengthExtension
85
+ * maxLength={500}
86
+ * mode="words"
87
+ * onLimitReached={(current, max) => {
88
+ * toast.error(`Maximum ${max} words exceeded`);
89
+ * }}
90
+ * onChange={(current, max, remaining) => {
91
+ * setCharCount(current);
92
+ * }}
93
+ * />
94
+ * ```
95
+ *
96
+ * @example
97
+ * With warning threshold:
98
+ * ```tsx
99
+ * <MaxLengthExtension
100
+ * maxLength={280}
101
+ * warningThreshold={0.9}
102
+ * onWarning={(current, max, remaining) => {
103
+ * toast.warning(`Only ${remaining} characters left`);
104
+ * }}
105
+ * />
106
+ * ```
107
+ *
108
+ * @example
109
+ * Custom counter (e.g., for Twitter-style emoji counting):
110
+ * ```tsx
111
+ * <MaxLengthExtension
112
+ * maxLength={280}
113
+ * customCounter={(text) => {
114
+ * // Twitter counts emoji as 2 characters
115
+ * const emojiRegex = /\p{Emoji}/gu;
116
+ * const emojiCount = (text.match(emojiRegex) || []).length;
117
+ * return text.length + emojiCount;
118
+ * }}
119
+ * />
120
+ * ```
121
+ */
122
+ declare function MaxLengthExtension({ maxLength, mode, onLimitReached, onChange, warningThreshold, onWarning, strategy, countWhitespace, customCounter, debug, }: MaxLengthExtensionProps): null;
123
+ declare namespace MaxLengthExtension {
124
+ var displayName: string;
125
+ }
126
+
127
+ export { MaxLengthExtension, type MaxLengthExtensionProps };
@@ -0,0 +1,127 @@
1
+ interface MaxLengthExtensionProps {
2
+ /**
3
+ * Maximum character limit
4
+ * @example 280 // Twitter-style limit
5
+ * @example 5000 // Long-form content
6
+ */
7
+ maxLength: number;
8
+ /**
9
+ * Character counting mode
10
+ * @default 'characters'
11
+ */
12
+ mode?: 'characters' | 'words' | 'bytes';
13
+ /**
14
+ * Callback when limit is reached
15
+ * @param current - Current character count
16
+ * @param max - Maximum allowed
17
+ * @param exceeded - Amount exceeded (if any)
18
+ */
19
+ onLimitReached?: (current: number, max: number, exceeded: number) => void;
20
+ /**
21
+ * Callback on every character change
22
+ * @param current - Current character count
23
+ * @param max - Maximum allowed
24
+ * @param remaining - Characters remaining
25
+ */
26
+ onChange?: (current: number, max: number, remaining: number) => void;
27
+ /**
28
+ * Whether to show a warning before hitting the limit
29
+ * @default 0.9 (90%)
30
+ */
31
+ warningThreshold?: number;
32
+ /**
33
+ * Callback when warning threshold is reached
34
+ */
35
+ onWarning?: (current: number, max: number, remaining: number) => void;
36
+ /**
37
+ * Strategy when limit is exceeded
38
+ * @default 'prevent' - Prevents further input
39
+ * @alternative 'trim' - Trims oldest content
40
+ * @alternative 'truncate' - Truncates from cursor position
41
+ */
42
+ strategy?: 'prevent' | 'trim' | 'truncate';
43
+ /**
44
+ * Whether to count whitespace
45
+ * @default true
46
+ */
47
+ countWhitespace?: boolean;
48
+ /**
49
+ * Custom character counter function
50
+ * Useful for emoji, unicode, or special counting rules
51
+ */
52
+ customCounter?: (text: string) => number;
53
+ /**
54
+ * Enable debug logging
55
+ * @default false
56
+ */
57
+ debug?: boolean;
58
+ }
59
+ /**
60
+ * MaxLengthExtension
61
+ *
62
+ * Enforces character/word limits in Lexical editor with flexible strategies
63
+ * and callbacks for UI feedback.
64
+ *
65
+ * Features:
66
+ * - Multiple counting modes (characters, words, bytes)
67
+ * - Configurable strategies (prevent, trim, truncate)
68
+ * - Warning thresholds
69
+ * - Custom counter support
70
+ * - Proper emoji/unicode handling
71
+ * - Memory-efficient with cleanup
72
+ *
73
+ * @example
74
+ * Basic usage:
75
+ * ```tsx
76
+ * <LexicalComposer>
77
+ * <MaxLengthExtension maxLength={280} />
78
+ * </LexicalComposer>
79
+ * ```
80
+ *
81
+ * @example
82
+ * With callbacks:
83
+ * ```tsx
84
+ * <MaxLengthExtension
85
+ * maxLength={500}
86
+ * mode="words"
87
+ * onLimitReached={(current, max) => {
88
+ * toast.error(`Maximum ${max} words exceeded`);
89
+ * }}
90
+ * onChange={(current, max, remaining) => {
91
+ * setCharCount(current);
92
+ * }}
93
+ * />
94
+ * ```
95
+ *
96
+ * @example
97
+ * With warning threshold:
98
+ * ```tsx
99
+ * <MaxLengthExtension
100
+ * maxLength={280}
101
+ * warningThreshold={0.9}
102
+ * onWarning={(current, max, remaining) => {
103
+ * toast.warning(`Only ${remaining} characters left`);
104
+ * }}
105
+ * />
106
+ * ```
107
+ *
108
+ * @example
109
+ * Custom counter (e.g., for Twitter-style emoji counting):
110
+ * ```tsx
111
+ * <MaxLengthExtension
112
+ * maxLength={280}
113
+ * customCounter={(text) => {
114
+ * // Twitter counts emoji as 2 characters
115
+ * const emojiRegex = /\p{Emoji}/gu;
116
+ * const emojiCount = (text.match(emojiRegex) || []).length;
117
+ * return text.length + emojiCount;
118
+ * }}
119
+ * />
120
+ * ```
121
+ */
122
+ declare function MaxLengthExtension({ maxLength, mode, onLimitReached, onChange, warningThreshold, onWarning, strategy, countWhitespace, customCounter, debug, }: MaxLengthExtensionProps): null;
123
+ declare namespace MaxLengthExtension {
124
+ var displayName: string;
125
+ }
126
+
127
+ export { MaxLengthExtension, type MaxLengthExtensionProps };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ 'use client'
2
+ import{useLexicalComposerContext as $}from"@lexical/react/LexicalComposerContext";import{$trimTextContentFromAnchor as T}from"@lexical/selection";import{$restoreEditorState as N}from"@lexical/utils";import{$getSelection as P,$isRangeSelection as W,RootNode as B}from"lexical";import{useCallback as z,useEffect as M,useRef as S}from"react";function D(t,a,c){switch(c||(t=t.replace(/\s/g,"")),a){case"words":return t.trim().split(/\s+/).filter(i=>i.length>0).length;case"bytes":return new Blob([t]).size;default:if(typeof Intl<"u"&&"Segmenter"in Intl)try{return[...new Intl.Segmenter().segment(t)].length}catch{console.warn("Intl.Segmenter not available, using fallback")}return A(t)}}function A(t){let a=t.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDFFF]/g);return a?a.length:0}function k({maxLength:t,mode:a="characters",onLimitReached:c,onChange:i,warningThreshold:h=.9,onWarning:p,strategy:m="prevent",countWhitespace:x=!0,customCounter:f,debug:d=!1}){let[s]=$(),b=S(null),g=S(!1),L=S({maxLength:t,mode:a,onLimitReached:c,onChange:i,warningThreshold:h,onWarning:p,strategy:m,countWhitespace:x,customCounter:f,debug:d});M(()=>{L.current={maxLength:t,mode:a,onLimitReached:c,onChange:i,warningThreshold:h,onWarning:p,strategy:m,countWhitespace:x,customCounter:f,debug:d}},[t,a,c,i,h,p,m,x,f,d]);let o=z((...C)=>{L.current.debug&&console.log("[MaxLength]",...C)},[]);return M(()=>{o("Registering max length extension",{maxLength:t,mode:a,strategy:m});let C=s.registerNodeTransform(B,u=>{let F=P();if(!W(F)||!F.isCollapsed())return;let e=L.current,l=s.getEditorState(),E=u.getTextContent(),n=e.customCounter?e.customCounter(E):D(E,e.mode,e.countWhitespace),v=l.read(()=>u.getTextContent()),y=e.customCounter?e.customCounter(v):D(v,e.mode,e.countWhitespace);if(o("Content length",{current:n,previous:y,max:e.maxLength}),n!==y&&e.onChange){let r=e.maxLength-n;e.onChange(n,e.maxLength,r)}let R=Math.floor(e.maxLength*e.warningThreshold);if(n>=R&&n<e.maxLength&&!g.current&&e.onWarning){g.current=!0;let r=e.maxLength-n;o("Warning threshold reached",{currentLength:n,warningLimit:R}),e.onWarning(n,e.maxLength,r)}if(n<R&&(g.current=!1),n>e.maxLength){let r=n-e.maxLength;o("Limit exceeded",{exceeded:r,strategy:e.strategy}),e.onLimitReached&&e.onLimitReached(n,e.maxLength,r);let w=F.anchor;switch(e.strategy){case"prevent":y===e.maxLength&&b.current!==l?(o("Restoring previous state"),b.current=l,N(s,l)):(o("Trimming from cursor",{amount:r}),T(s,w,r));break;case"trim":o("Trimming from cursor",{amount:r}),T(s,w,r);break;case"truncate":o("Truncating from end",{amount:r}),s.update(()=>{let I=E.slice(0,e.maxLength);u.clear(),u.append(s.parseEditorState(JSON.stringify({root:{children:[{type:"paragraph",children:[{type:"text",text:I}]}]}})).read(()=>u))});break}}});return()=>{o("Unregistering max length extension"),C(),b.current=null,g.current=!1}},[s,o]),null}k.displayName="Typix.MaxLengthExtension";export{k as MaxLengthExtension};
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@typix-editor/extension-max-length",
3
+ "version": "1.0.0",
4
+ "description": "Max length extension for Typix",
5
+ "keywords": [],
6
+ "author": "Diyorbek Juraev <mrdiyorbekjuraev@gmail.com>",
7
+ "homepage": "https://typix.com",
8
+ "license": "MIT",
9
+ "type": "module",
10
+ "main": "dist/index.cjs",
11
+ "module": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "sideEffects": false,
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "publishConfig": {
18
+ "access": "public"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/mrdiyorbek-juraev/typix.git"
23
+ },
24
+ "bugs": {
25
+ "url": "https://github.com/mrdiyorbek-juraev/typix/issues"
26
+ },
27
+ "peerDependencies": {
28
+ "react": "^18.2.0 || ^19.0.0-0",
29
+ "react-dom": "^18.2.0 || ^19.0.0-0",
30
+ "@typix-editor/react": "2.0.1"
31
+ },
32
+ "devDependencies": {
33
+ "@lexical/react": "^0.39.0",
34
+ "@types/react": "^19.2.7",
35
+ "@types/react-dom": "^19.2.1",
36
+ "@lexical/utils": "^0.39.0",
37
+ "@lexical/selection": "^0.39.0",
38
+ "lexical": "^0.39.0",
39
+ "react": "^18.2.0 || ^19.0.0-0",
40
+ "react-dom": "^18.2.0 || ^19.0.0-0"
41
+ },
42
+ "scripts": {
43
+ "build": "tsup",
44
+ "build:fast": "tsup",
45
+ "dev": "pnpm build:fast --watch",
46
+ "clean": "git clean -xdf .cache .turbo dist node_modules rm -rf dist",
47
+ "typecheck": "tsc --noEmit --emitDeclarationOnly false"
48
+ }
49
+ }