@fluixi-css/language 1.0.0-next.5

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.
@@ -0,0 +1,76 @@
1
+ import { type CssContext, type Registry } from '@fluixi-css/core';
2
+ import { type Rgba } from './color';
3
+ export interface Range {
4
+ start: number;
5
+ end: number;
6
+ }
7
+ export type CompletionKind = 'utility' | 'variant' | 'directive' | 'variable';
8
+ export interface Completion {
9
+ label: string;
10
+ kind: CompletionKind;
11
+ range: Range;
12
+ /** Replaces `label` when they differ: a variant inserts `hover:`. */
13
+ insertText?: string;
14
+ detail?: string;
15
+ documentation?: string;
16
+ /** The colour it stands for, for a swatch. */
17
+ color?: Rgba;
18
+ }
19
+ export interface Hover {
20
+ range: Range;
21
+ /** CSS to show: what a class compiles to, or a theme variable's declaration. */
22
+ css: string;
23
+ }
24
+ export interface Diagnostic {
25
+ range: Range;
26
+ message: string;
27
+ severity: 'error' | 'warning';
28
+ }
29
+ export interface ColorInfo {
30
+ range: Range;
31
+ color: Rgba;
32
+ }
33
+ export interface LanguageServiceOptions {
34
+ /** The project's theme CSS (`@theme`, `@utility`, `@custom-variant`). */
35
+ theme?: string;
36
+ /** An existing context instead, such as the one a build already holds. */
37
+ context?: CssContext;
38
+ }
39
+ export interface LanguageService {
40
+ readonly registry: Registry;
41
+ /** Completions for the class being typed, `partial`, which starts at `start`. */
42
+ completeClass(partial: string, start: number): Completion[];
43
+ /** What a class compiles to, or null when it compiles to nothing. */
44
+ classCss(cls: string): string | null;
45
+ /** The colour a class sets, when it sets one. */
46
+ classColor(cls: string): Rgba | null;
47
+ /** Why a class at `start` produces nothing, or null when it is fine. */
48
+ checkClass(cls: string, start: number): Diagnostic | null;
49
+ /** Completions at `offset` in a stylesheet. */
50
+ complete(css: string, offset: number): Completion[];
51
+ hover(css: string, offset: number): Hover | null;
52
+ diagnostics(css: string): Diagnostic[];
53
+ colors(css: string): ColorInfo[];
54
+ }
55
+ export declare const DIRECTIVES: {
56
+ name: string;
57
+ documentation: string;
58
+ }[];
59
+ /**
60
+ * Fluixi's at-rules and pseudo-classes in the CSS custom data format editors read
61
+ * (`css.customData` in VS Code, `newCSSDataProvider` in vscode-css-languageservice), so a
62
+ * stock CSS service stops flagging `@apply` or `:deep()` as unknown.
63
+ */
64
+ export declare const CSS_CUSTOM_DATA: {
65
+ version: number;
66
+ atDirectives: {
67
+ name: string;
68
+ description: string;
69
+ }[];
70
+ pseudoClasses: {
71
+ name: string;
72
+ description: string;
73
+ }[];
74
+ };
75
+ export declare function createLanguageService(options?: LanguageServiceOptions): LanguageService;
76
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1,279 @@
1
+ // Editor-agnostic language support for Fluixi CSS: what an editor asks about a stylesheet or a
2
+ // class list, answered from the same context the build compiles with. Positions are offsets into
3
+ // the text handed in; an editor integration maps them to its own.
4
+ import { compileClasses, createCssContext, parseAtom, parseVariant, splitAtTopLevel, } from '@fluixi-css/core';
5
+ import { classCandidates } from './candidates';
6
+ import { parseColor } from './color';
7
+ export const DIRECTIVES = [
8
+ { name: 'apply', documentation: 'Inline utilities into this rule: `@apply p-4 rounded-xl hover:shadow-md;`' },
9
+ { name: 'theme', documentation: 'Declare theme variables (`--color-*`, `--spacing`, …) that utilities read.' },
10
+ { name: 'utility', documentation: 'Define a utility: `@utility tab-4 { tab-size: 4; }`, or `@utility tab-* { … }` for one that takes a value.' },
11
+ { name: 'custom-variant', documentation: 'Define a variant: `@custom-variant theme-dark (&:where([data-theme=dark] *));`' },
12
+ { name: 'source', documentation: 'Scan more files for class names: `@source "../components";`' },
13
+ { name: 'fluixi', documentation: 'Where the generated theme variables and utilities go in this stylesheet.' },
14
+ ];
15
+ const DIRECTIVE_DOCS = new Map(DIRECTIVES.map((d) => [d.name, d.documentation]));
16
+ /**
17
+ * Fluixi's at-rules and pseudo-classes in the CSS custom data format editors read
18
+ * (`css.customData` in VS Code, `newCSSDataProvider` in vscode-css-languageservice), so a
19
+ * stock CSS service stops flagging `@apply` or `:deep()` as unknown.
20
+ */
21
+ export const CSS_CUSTOM_DATA = {
22
+ version: 1.1,
23
+ atDirectives: [
24
+ ...DIRECTIVES.map((d) => ({ name: `@${d.name}`, description: d.documentation })),
25
+ { name: '@slot', description: 'Inside `@custom-variant`: where the rule it wraps goes.' },
26
+ ],
27
+ pseudoClasses: [
28
+ { name: ':global', description: 'In a scoped `<style>`: this selector is left unscoped.' },
29
+ { name: ':deep', description: 'In a scoped `<style>`: reaches elements a child component renders.' },
30
+ ],
31
+ };
32
+ // Comments and string contents blanked to spaces, so offsets stay put and nothing inside
33
+ // them reads as a directive or a reference.
34
+ function mask(css) {
35
+ let out = '';
36
+ let i = 0;
37
+ while (i < css.length) {
38
+ if (css.startsWith('/*', i)) {
39
+ const end = css.indexOf('*/', i + 2);
40
+ const stop = end === -1 ? css.length : end + 2;
41
+ out += css.slice(i, stop).replace(/[^\n]/g, ' ');
42
+ i = stop;
43
+ }
44
+ else if (css[i] === '"' || css[i] === "'") {
45
+ const quote = css[i];
46
+ let j = i + 1;
47
+ while (j < css.length && css[j] !== quote && css[j] !== '\n')
48
+ j += css[j] === '\\' ? 2 : 1;
49
+ out += quote + ' '.repeat(Math.max(0, Math.min(j, css.length) - i - 1)) + (j < css.length ? css[j] : '');
50
+ i = j + 1;
51
+ }
52
+ else {
53
+ out += css[i];
54
+ i++;
55
+ }
56
+ }
57
+ return out.slice(0, css.length);
58
+ }
59
+ /** The class words of every `@apply`, with their offsets. */
60
+ function applyWords(masked) {
61
+ const words = [];
62
+ const re = /@apply\b/g;
63
+ for (let m = re.exec(masked); m; m = re.exec(masked)) {
64
+ let i = m.index + m[0].length;
65
+ while (i < masked.length && !';{}'.includes(masked[i])) {
66
+ if (/\s/.test(masked[i])) {
67
+ i++;
68
+ continue;
69
+ }
70
+ const start = i;
71
+ while (i < masked.length && !/\s/.test(masked[i]) && !';{}'.includes(masked[i]))
72
+ i++;
73
+ words.push({ text: masked.slice(start, i), start, end: i });
74
+ }
75
+ }
76
+ return words;
77
+ }
78
+ /** Every `var(--name` reference, the name's range. */
79
+ function varRefs(masked) {
80
+ const refs = [];
81
+ const re = /var\(\s*(--[\w-]+)/g;
82
+ for (let m = re.exec(masked); m; m = re.exec(masked)) {
83
+ const start = m.index + m[0].length - m[1].length;
84
+ refs.push({ text: m[1], start, end: start + m[1].length });
85
+ }
86
+ return refs;
87
+ }
88
+ export function createLanguageService(options = {}) {
89
+ const context = options.context ?? createCssContext(options.theme ? { theme: options.theme } : {});
90
+ const reg = context.registry;
91
+ let candidates;
92
+ const all = () => (candidates ?? (candidates = classCandidates(reg)));
93
+ // A theme value with its `var()` references followed, for a colour or a hover.
94
+ const resolveValue = (value, depth = 0) => depth > 8
95
+ ? value
96
+ : value.replace(/var\(\s*(--[\w-]+)\s*(?:,[^)]*)?\)/g, (whole, name) => {
97
+ const v = reg.theme.get(name);
98
+ return v === undefined ? whole : resolveValue(v, depth + 1);
99
+ });
100
+ // `var(--radius-xl)` says nothing on its own: the theme's value goes beside it.
101
+ const annotate = (css) => css.replace(/var\(\s*(--[\w-]+)\s*\)/g, (whole, name) => {
102
+ const value = reg.theme.get(name);
103
+ return value === undefined ? whole : `${whole} /* ${resolveValue(value)} */`;
104
+ });
105
+ const classCss = (cls) => {
106
+ const css = compileClasses([cls], reg);
107
+ return css.trim() ? annotate(css) : null;
108
+ };
109
+ const classColor = (cls) => {
110
+ const css = compileClasses([cls], reg, { minify: true });
111
+ for (const m of css.matchAll(/:([^;{}]+)[;}]/g)) {
112
+ const color = parseColor(resolveValue(m[1].replace(/!important$/, '').trim()));
113
+ if (color)
114
+ return color;
115
+ }
116
+ return null;
117
+ };
118
+ // Any utility-shaped name parses; a known one is a rule, or a registered root with a value.
119
+ const isKnownUtility = (utility) => {
120
+ const bare = utility.replace(/^[!-]+|!$/g, '');
121
+ if (reg.isRule(bare) || bare.startsWith('['))
122
+ return true;
123
+ return reg.names().dynamicRules.some((root) => bare === root || bare.startsWith(`${root}-`));
124
+ };
125
+ const checkClass = (cls, start) => {
126
+ const range = { start, end: start + cls.length };
127
+ if (/^\[.*\]$/.test(cls))
128
+ return null;
129
+ if (classCss(cls))
130
+ return null;
131
+ const parts = splitAtTopLevel(cls, ':');
132
+ const utility = parts[parts.length - 1];
133
+ const variants = parts.slice(0, -1);
134
+ const utilityStart = start + cls.length - utility.length;
135
+ if (!parseAtom(utility, reg) || !isKnownUtility(utility)) {
136
+ return { range: { start: utilityStart, end: utilityStart + utility.length }, message: `Unknown utility '${utility}'.`, severity: 'error' };
137
+ }
138
+ if (!classCss(utility)) {
139
+ return { range, message: `'${utility}' produces no CSS: no theme value or rule matches it.`, severity: 'error' };
140
+ }
141
+ // The utility works alone, so a variant is what fails. A variant-shaped name parses
142
+ // whether or not it exists; compiling it with the utility is what tells.
143
+ let offset = start;
144
+ for (const variant of variants) {
145
+ if (!parseVariant(variant, reg) || !classCss(`${variant}:${utility}`)) {
146
+ return { range: { start: offset, end: offset + variant.length }, message: `Unknown variant '${variant}'.`, severity: 'error' };
147
+ }
148
+ offset += variant.length + 1;
149
+ }
150
+ return { range, message: `'${cls}' produces no CSS.`, severity: 'error' };
151
+ };
152
+ const completeClass = (partial, start) => {
153
+ const parts = splitAtTopLevel(partial, ':');
154
+ const current = parts[parts.length - 1] ?? '';
155
+ // `!` and `-` lead a class (`!p-4`, `-mt-2`) and stay as written.
156
+ const lead = /^[!-]*/.exec(current)[0];
157
+ const typed = current.slice(lead.length);
158
+ const range = { start: start + partial.length - typed.length, end: start + partial.length };
159
+ const root = typed.split('-')[0] ?? '';
160
+ const out = [];
161
+ for (const c of all()) {
162
+ if (root && !c.name.startsWith(root))
163
+ continue;
164
+ const value = c.token ? reg.theme.get(c.token) : undefined;
165
+ const color = value ? parseColor(resolveValue(value)) : null;
166
+ out.push({
167
+ label: c.name,
168
+ kind: 'utility',
169
+ range,
170
+ ...(value ? { detail: value } : {}),
171
+ ...(color ? { color } : {}),
172
+ });
173
+ }
174
+ const { variants, dynamicVariants } = reg.names();
175
+ for (const v of variants) {
176
+ if (root && !v.startsWith(root))
177
+ continue;
178
+ out.push({ label: `${v}:`, kind: 'variant', range });
179
+ }
180
+ for (const v of dynamicVariants) {
181
+ if (root && !v.startsWith(root))
182
+ continue;
183
+ out.push({ label: `${v}-`, kind: 'variant', range, detail: 'takes a value' });
184
+ }
185
+ return out;
186
+ };
187
+ const themeCompletions = (range) => reg.theme.entries().map(([name, value]) => {
188
+ const color = parseColor(resolveValue(value));
189
+ return { label: name, kind: 'variable', range, detail: value, ...(color ? { color } : {}) };
190
+ });
191
+ return {
192
+ registry: reg,
193
+ completeClass,
194
+ classCss,
195
+ classColor,
196
+ checkClass,
197
+ complete(css, offset) {
198
+ const masked = mask(css);
199
+ const before = masked.slice(0, offset);
200
+ const directive = /@([\w-]*)$/.exec(before);
201
+ if (directive) {
202
+ const range = { start: offset - directive[1].length, end: offset };
203
+ return DIRECTIVES.map((d) => ({ label: d.name, kind: 'directive', range, documentation: d.documentation }));
204
+ }
205
+ const variable = /var\(\s*(--[\w-]*|-?)$/.exec(before);
206
+ if (variable)
207
+ return themeCompletions({ start: offset - variable[1].length, end: offset });
208
+ const apply = before.lastIndexOf('@apply');
209
+ if (apply !== -1 && !/[;{}]/.test(before.slice(apply))) {
210
+ const word = /[^\s]*$/.exec(before)[0];
211
+ if (offset - word.length > apply + 5)
212
+ return completeClass(word, offset - word.length);
213
+ }
214
+ return [];
215
+ },
216
+ hover(css, offset) {
217
+ const masked = mask(css);
218
+ for (const w of applyWords(masked)) {
219
+ if (offset < w.start || offset > w.end)
220
+ continue;
221
+ const out = classCss(w.text);
222
+ return out ? { range: { start: w.start, end: w.end }, css: out } : null;
223
+ }
224
+ for (const r of varRefs(masked)) {
225
+ if (offset < r.start || offset > r.end)
226
+ continue;
227
+ const value = reg.theme.get(r.text);
228
+ return value === undefined ? null : { range: { start: r.start, end: r.end }, css: `${r.text}: ${value};` };
229
+ }
230
+ const at = /@([\w-]+)/g;
231
+ for (let m = at.exec(masked); m; m = at.exec(masked)) {
232
+ const doc = DIRECTIVE_DOCS.get(m[1]);
233
+ if (doc && offset >= m.index && offset <= m.index + m[0].length) {
234
+ return { range: { start: m.index, end: m.index + m[0].length }, css: `/* ${doc} */` };
235
+ }
236
+ }
237
+ return null;
238
+ },
239
+ diagnostics(css) {
240
+ const masked = mask(css);
241
+ const out = [];
242
+ for (const w of applyWords(masked)) {
243
+ const d = checkClass(w.text, w.start);
244
+ if (d)
245
+ out.push(d);
246
+ }
247
+ // A theme-shaped reference (`--color-…`) to a key the theme does not have, and that this
248
+ // stylesheet does not declare either: most likely a typo in a token name.
249
+ const declared = new Set([...masked.matchAll(/(--[\w-]+)\s*:/g)].map((m) => m[1]));
250
+ const spaces = new Set(reg.theme.entries().map(([name]) => name.slice(2).split('-')[0]));
251
+ for (const r of varRefs(masked)) {
252
+ if (reg.theme.has(r.text) || declared.has(r.text))
253
+ continue;
254
+ const ns = r.text.slice(2).split('-')[0];
255
+ if (!spaces.has(ns) || r.text === `--${ns}`)
256
+ continue;
257
+ out.push({ range: { start: r.start, end: r.end }, message: `${r.text} is not in the theme.`, severity: 'warning' });
258
+ }
259
+ return out;
260
+ },
261
+ colors(css) {
262
+ const masked = mask(css);
263
+ const out = [];
264
+ for (const w of applyWords(masked)) {
265
+ const color = classColor(w.text);
266
+ if (color)
267
+ out.push({ range: { start: w.start, end: w.end }, color });
268
+ }
269
+ for (const r of varRefs(masked)) {
270
+ const value = reg.theme.get(r.text);
271
+ const color = value ? parseColor(resolveValue(value)) : null;
272
+ if (color)
273
+ out.push({ range: { start: r.start, end: r.end }, color });
274
+ }
275
+ return out;
276
+ },
277
+ };
278
+ }
279
+ //# sourceMappingURL=service.js.map
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@fluixi-css/language",
3
+ "version": "1.0.0-next.5",
4
+ "description": "Completion, hover, diagnostics and colours for Fluixi CSS, for any editor integration",
5
+ "license": "MIT",
6
+ "author": "fluixi",
7
+ "files": [
8
+ "dist",
9
+ "README.md",
10
+ "LICENSE",
11
+ "!dist/**/*.map"
12
+ ],
13
+ "main": "./dist/src/index.js",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/src/index.d.ts",
17
+ "import": "./dist/src/index.mjs",
18
+ "require": "./dist/src/index.cjs"
19
+ }
20
+ },
21
+ "private": false,
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/fluixi/css.git"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public",
28
+ "registry": "https://registry.npmjs.org/"
29
+ },
30
+ "keywords": [
31
+ "fluixi",
32
+ "css",
33
+ "language-server",
34
+ "intellisense"
35
+ ],
36
+ "dependencies": {
37
+ "@fluixi-css/core": "1.0.0-next.5"
38
+ },
39
+ "devDependencies": {
40
+ "vitest": "^4.1.10"
41
+ },
42
+ "scripts": {
43
+ "build:typings": "cross-env tsc --project ./tsconfig.json --declarationDir dist",
44
+ "build:rollup": "pnpm run build:typings && cross-env NODE_ENV=production INPUT_FILE=./src/index.ts rollup -c ../configs/rollup.config.mjs",
45
+ "build": "pnpm run build:rollup && tsc",
46
+ "test": "vitest run"
47
+ }
48
+ }