@unocss/autocomplete 0.29.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) 2021 Anthony Fu <https://github.com/antfu>
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
@@ -0,0 +1,9 @@
1
+ # @unocss/autocomplete
2
+
3
+ Autocomplete utils for UnoCSS.
4
+
5
+ > WIP
6
+
7
+ ## License
8
+
9
+ MIT License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)
package/dist/index.cjs ADDED
@@ -0,0 +1,187 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const core = require('@unocss/core');
6
+ const LRU = require('lru-cache');
7
+
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
9
+
10
+ const LRU__default = /*#__PURE__*/_interopDefaultLegacy(LRU);
11
+
12
+ const shorthands = {
13
+ num: `(${[0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 24, 36].join("|")})`,
14
+ precent: `(${[0, 25, 50, 45, 100].join("|")})`,
15
+ directions: "(x|y|t|b|l|r|s|e)"
16
+ };
17
+ function handleRegexMatch(str, regex, onMatched, onNotMatched) {
18
+ let lastIndex = 0;
19
+ Array.from(str.matchAll(regex)).forEach((m) => {
20
+ const index = m.index;
21
+ if (lastIndex !== index)
22
+ onNotMatched(str.slice(lastIndex, index), lastIndex, index);
23
+ onMatched(m);
24
+ lastIndex = index + m[0].length;
25
+ });
26
+ if (lastIndex !== str.length)
27
+ onNotMatched(str.slice(lastIndex), lastIndex, str.length);
28
+ }
29
+ function parseAutocomplete(template, theme = {}) {
30
+ const parts = [];
31
+ template = template.replace(/<(\w+)>/g, (_, key) => {
32
+ if (!shorthands[key])
33
+ throw new Error(`Unknown template shorthand: ${key}`);
34
+ return shorthands[key];
35
+ });
36
+ handleGroups(template);
37
+ return {
38
+ parts,
39
+ suggest
40
+ };
41
+ function handleNonGroup(input) {
42
+ handleRegexMatch(input, /\$([\w\|]+)/g, (m) => {
43
+ const keys = m[1].split("|");
44
+ parts.push({
45
+ type: "theme",
46
+ objects: keys.map((i) => {
47
+ if (!i || !theme[i])
48
+ throw new Error(`Invalid theme key ${i}`);
49
+ return theme[i];
50
+ })
51
+ });
52
+ }, (str) => {
53
+ parts.push({
54
+ type: "static",
55
+ value: str
56
+ });
57
+ });
58
+ }
59
+ function handleGroups(input) {
60
+ handleRegexMatch(input, /\((.*?)\)/g, (m) => {
61
+ parts.push({
62
+ type: "group",
63
+ values: m[1].split("|").sort((a, b) => b.length - a.length)
64
+ });
65
+ }, (str) => {
66
+ handleNonGroup(str);
67
+ });
68
+ }
69
+ function suggest(input) {
70
+ let rest = input;
71
+ let matched = "";
72
+ let combinations = [];
73
+ const tempParts = [...parts];
74
+ while (tempParts.length) {
75
+ const part = tempParts.shift();
76
+ if (part.type === "static") {
77
+ if (!rest.startsWith(part.value))
78
+ break;
79
+ matched += part.value;
80
+ rest = rest.slice(part.value.length);
81
+ } else if (part.type === "group") {
82
+ const fullMatched = part.values.find((i) => i && rest.startsWith(i));
83
+ if (fullMatched != null) {
84
+ matched += fullMatched;
85
+ rest = rest.slice(fullMatched.length);
86
+ } else {
87
+ combinations = part.values.filter((i) => i.startsWith(rest));
88
+ break;
89
+ }
90
+ } else if (part.type === "theme") {
91
+ const keys = part.objects.flatMap((i) => Object.keys(i));
92
+ const fullMatched = keys.find((i) => i && rest.startsWith(i));
93
+ if (fullMatched != null) {
94
+ matched += fullMatched;
95
+ rest = rest.slice(fullMatched.length);
96
+ const subObjects = part.objects.map((i) => i[fullMatched]).filter((i) => !!i && typeof i === "object");
97
+ if (subObjects.length) {
98
+ tempParts.unshift({
99
+ type: "static",
100
+ value: "-"
101
+ }, {
102
+ type: "theme",
103
+ objects: subObjects
104
+ });
105
+ }
106
+ } else {
107
+ combinations = keys.filter((i) => i.startsWith(rest));
108
+ break;
109
+ }
110
+ }
111
+ }
112
+ if (!matched)
113
+ return [];
114
+ if (combinations.length === 0)
115
+ combinations.push("");
116
+ return combinations.map((i) => matched + i).filter((i) => i.length >= input.length);
117
+ }
118
+ }
119
+
120
+ function createAutocomplete(uno) {
121
+ const templateCache = /* @__PURE__ */ new Map();
122
+ const cache = new LRU__default({ max: 1e3 });
123
+ let staticUtils = [];
124
+ let templates = [];
125
+ function getParsed(template) {
126
+ if (!templateCache.has(template))
127
+ templateCache.set(template, parseAutocomplete(template, uno.config.theme));
128
+ return templateCache.get(template).suggest;
129
+ }
130
+ async function suggest(input) {
131
+ if (input.length < 2)
132
+ return [];
133
+ if (cache.has(input))
134
+ return cache.get(input);
135
+ const result = await Promise.all([
136
+ suggestSelf(input),
137
+ suggestStatic(input),
138
+ ...suggestFromPreset(input)
139
+ ]).then((i) => core.uniq(i.flat()).sort().filter(Boolean));
140
+ cache.set(input, result);
141
+ return result;
142
+ }
143
+ async function suggestSelf(input) {
144
+ const i = await uno.parseToken(input, "-");
145
+ return i ? [input] : [];
146
+ }
147
+ async function suggestStatic(input) {
148
+ return staticUtils.filter((i) => i.startsWith(input));
149
+ }
150
+ function suggestFromPreset(input) {
151
+ return templates.map((fn) => typeof fn === "function" ? fn(input) : getParsed(fn)(input)) || [];
152
+ }
153
+ function reset() {
154
+ templateCache.clear();
155
+ cache.clear();
156
+ staticUtils = Object.keys(uno.config.rulesStaticMap);
157
+ templates = [
158
+ ...uno.config.autocomplete || [],
159
+ ...uno.config.rulesDynamic.flatMap((i) => core.toArray(i?.[2]?.autocomplete || []))
160
+ ];
161
+ }
162
+ reset();
163
+ return {
164
+ suggest,
165
+ templates,
166
+ cache,
167
+ reset
168
+ };
169
+ }
170
+
171
+ function searchUsageBoundary(line, index) {
172
+ let start = index;
173
+ let end = index;
174
+ while (start && /[^\s"']/.test(line.charAt(start - 1)))
175
+ --start;
176
+ while (end < line.length && /[^\s"']/.test(line.charAt(end)))
177
+ ++end;
178
+ return {
179
+ content: line.slice(start, end),
180
+ start,
181
+ end
182
+ };
183
+ }
184
+
185
+ exports.createAutocomplete = createAutocomplete;
186
+ exports.parseAutocomplete = parseAutocomplete;
187
+ exports.searchUsageBoundary = searchUsageBoundary;
@@ -0,0 +1,37 @@
1
+ import { UnoGenerator, AutoCompleteFunction } from '@unocss/core';
2
+ import LRU from 'lru-cache';
3
+
4
+ declare function createAutocomplete(uno: UnoGenerator): {
5
+ suggest: (input: string) => Promise<string[] | undefined>;
6
+ templates: (string | AutoCompleteFunction)[];
7
+ cache: LRU<string, string[]>;
8
+ reset: () => void;
9
+ };
10
+
11
+ declare type AutocompleteTemplatePart = AutocompleteTemplateStatic | AutocompleteTemplateGroup | AutocompleteTemplateTheme;
12
+ interface AutocompleteTemplateStatic {
13
+ type: 'static';
14
+ value: string;
15
+ }
16
+ interface AutocompleteTemplateGroup {
17
+ type: 'group';
18
+ values: string[];
19
+ }
20
+ interface AutocompleteTemplateTheme {
21
+ type: 'theme';
22
+ objects: Record<string, unknown>[];
23
+ }
24
+ interface ParsedAutocompleteTemplate {
25
+ parts: AutocompleteTemplatePart[];
26
+ suggest(input: string): string[] | undefined;
27
+ }
28
+
29
+ declare function parseAutocomplete(template: string, theme?: any): ParsedAutocompleteTemplate;
30
+
31
+ declare function searchUsageBoundary(line: string, index: number): {
32
+ content: string;
33
+ start: number;
34
+ end: number;
35
+ };
36
+
37
+ export { AutocompleteTemplateGroup, AutocompleteTemplatePart, AutocompleteTemplateStatic, AutocompleteTemplateTheme, ParsedAutocompleteTemplate, createAutocomplete, parseAutocomplete, searchUsageBoundary };
package/dist/index.mjs ADDED
@@ -0,0 +1,177 @@
1
+ import { uniq, toArray } from '@unocss/core';
2
+ import LRU from 'lru-cache';
3
+
4
+ const shorthands = {
5
+ num: `(${[0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 24, 36].join("|")})`,
6
+ precent: `(${[0, 25, 50, 45, 100].join("|")})`,
7
+ directions: "(x|y|t|b|l|r|s|e)"
8
+ };
9
+ function handleRegexMatch(str, regex, onMatched, onNotMatched) {
10
+ let lastIndex = 0;
11
+ Array.from(str.matchAll(regex)).forEach((m) => {
12
+ const index = m.index;
13
+ if (lastIndex !== index)
14
+ onNotMatched(str.slice(lastIndex, index), lastIndex, index);
15
+ onMatched(m);
16
+ lastIndex = index + m[0].length;
17
+ });
18
+ if (lastIndex !== str.length)
19
+ onNotMatched(str.slice(lastIndex), lastIndex, str.length);
20
+ }
21
+ function parseAutocomplete(template, theme = {}) {
22
+ const parts = [];
23
+ template = template.replace(/<(\w+)>/g, (_, key) => {
24
+ if (!shorthands[key])
25
+ throw new Error(`Unknown template shorthand: ${key}`);
26
+ return shorthands[key];
27
+ });
28
+ handleGroups(template);
29
+ return {
30
+ parts,
31
+ suggest
32
+ };
33
+ function handleNonGroup(input) {
34
+ handleRegexMatch(input, /\$([\w\|]+)/g, (m) => {
35
+ const keys = m[1].split("|");
36
+ parts.push({
37
+ type: "theme",
38
+ objects: keys.map((i) => {
39
+ if (!i || !theme[i])
40
+ throw new Error(`Invalid theme key ${i}`);
41
+ return theme[i];
42
+ })
43
+ });
44
+ }, (str) => {
45
+ parts.push({
46
+ type: "static",
47
+ value: str
48
+ });
49
+ });
50
+ }
51
+ function handleGroups(input) {
52
+ handleRegexMatch(input, /\((.*?)\)/g, (m) => {
53
+ parts.push({
54
+ type: "group",
55
+ values: m[1].split("|").sort((a, b) => b.length - a.length)
56
+ });
57
+ }, (str) => {
58
+ handleNonGroup(str);
59
+ });
60
+ }
61
+ function suggest(input) {
62
+ let rest = input;
63
+ let matched = "";
64
+ let combinations = [];
65
+ const tempParts = [...parts];
66
+ while (tempParts.length) {
67
+ const part = tempParts.shift();
68
+ if (part.type === "static") {
69
+ if (!rest.startsWith(part.value))
70
+ break;
71
+ matched += part.value;
72
+ rest = rest.slice(part.value.length);
73
+ } else if (part.type === "group") {
74
+ const fullMatched = part.values.find((i) => i && rest.startsWith(i));
75
+ if (fullMatched != null) {
76
+ matched += fullMatched;
77
+ rest = rest.slice(fullMatched.length);
78
+ } else {
79
+ combinations = part.values.filter((i) => i.startsWith(rest));
80
+ break;
81
+ }
82
+ } else if (part.type === "theme") {
83
+ const keys = part.objects.flatMap((i) => Object.keys(i));
84
+ const fullMatched = keys.find((i) => i && rest.startsWith(i));
85
+ if (fullMatched != null) {
86
+ matched += fullMatched;
87
+ rest = rest.slice(fullMatched.length);
88
+ const subObjects = part.objects.map((i) => i[fullMatched]).filter((i) => !!i && typeof i === "object");
89
+ if (subObjects.length) {
90
+ tempParts.unshift({
91
+ type: "static",
92
+ value: "-"
93
+ }, {
94
+ type: "theme",
95
+ objects: subObjects
96
+ });
97
+ }
98
+ } else {
99
+ combinations = keys.filter((i) => i.startsWith(rest));
100
+ break;
101
+ }
102
+ }
103
+ }
104
+ if (!matched)
105
+ return [];
106
+ if (combinations.length === 0)
107
+ combinations.push("");
108
+ return combinations.map((i) => matched + i).filter((i) => i.length >= input.length);
109
+ }
110
+ }
111
+
112
+ function createAutocomplete(uno) {
113
+ const templateCache = /* @__PURE__ */ new Map();
114
+ const cache = new LRU({ max: 1e3 });
115
+ let staticUtils = [];
116
+ let templates = [];
117
+ function getParsed(template) {
118
+ if (!templateCache.has(template))
119
+ templateCache.set(template, parseAutocomplete(template, uno.config.theme));
120
+ return templateCache.get(template).suggest;
121
+ }
122
+ async function suggest(input) {
123
+ if (input.length < 2)
124
+ return [];
125
+ if (cache.has(input))
126
+ return cache.get(input);
127
+ const result = await Promise.all([
128
+ suggestSelf(input),
129
+ suggestStatic(input),
130
+ ...suggestFromPreset(input)
131
+ ]).then((i) => uniq(i.flat()).sort().filter(Boolean));
132
+ cache.set(input, result);
133
+ return result;
134
+ }
135
+ async function suggestSelf(input) {
136
+ const i = await uno.parseToken(input, "-");
137
+ return i ? [input] : [];
138
+ }
139
+ async function suggestStatic(input) {
140
+ return staticUtils.filter((i) => i.startsWith(input));
141
+ }
142
+ function suggestFromPreset(input) {
143
+ return templates.map((fn) => typeof fn === "function" ? fn(input) : getParsed(fn)(input)) || [];
144
+ }
145
+ function reset() {
146
+ templateCache.clear();
147
+ cache.clear();
148
+ staticUtils = Object.keys(uno.config.rulesStaticMap);
149
+ templates = [
150
+ ...uno.config.autocomplete || [],
151
+ ...uno.config.rulesDynamic.flatMap((i) => toArray(i?.[2]?.autocomplete || []))
152
+ ];
153
+ }
154
+ reset();
155
+ return {
156
+ suggest,
157
+ templates,
158
+ cache,
159
+ reset
160
+ };
161
+ }
162
+
163
+ function searchUsageBoundary(line, index) {
164
+ let start = index;
165
+ let end = index;
166
+ while (start && /[^\s"']/.test(line.charAt(start - 1)))
167
+ --start;
168
+ while (end < line.length && /[^\s"']/.test(line.charAt(end)))
169
+ ++end;
170
+ return {
171
+ content: line.slice(start, end),
172
+ start,
173
+ end
174
+ };
175
+ }
176
+
177
+ export { createAutocomplete, parseAutocomplete, searchUsageBoundary };
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@unocss/autocomplete",
3
+ "version": "0.29.0",
4
+ "description": "Autocomplete utils for UnoCSS",
5
+ "keywords": [
6
+ "unocss",
7
+ "autocomplete"
8
+ ],
9
+ "homepage": "https://github.com/unocss/unocss/tree/main/packages/autocomplete#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/unocss/unocss/issues"
12
+ },
13
+ "license": "MIT",
14
+ "author": "Anthony Fu <anthonyfu117@hotmail.com>",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/unocss/unocss.git",
18
+ "directory": "packages/autocomplete"
19
+ },
20
+ "funding": "https://github.com/sponsors/antfu",
21
+ "main": "./dist/index.cjs",
22
+ "module": "./dist/index.mjs",
23
+ "types": "./dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "require": "./dist/index.cjs",
27
+ "import": "./dist/index.mjs"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "sideEffects": false,
34
+ "dependencies": {
35
+ "lru-cache": "^7.5.1"
36
+ },
37
+ "devDependencies": {
38
+ "@types/lru-cache": "^7.4.0",
39
+ "@unocss/core": "0.29.0"
40
+ },
41
+ "scripts": {
42
+ "build": "unbuild",
43
+ "stub": "unbuild --stub"
44
+ },
45
+ "readme": "# @unocss/autocomplete\n\nAutocomplete utils for UnoCSS.\n\n> WIP\n\n## License\n\nMIT License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)\n"
46
+ }