apps/glyph Public The code is public; the app answers only to 1 person who can change it and the crew.

Files 5c2d82ded0cf18c81c70d9f4a3f1de0b1688b125
190 lines · 9.4 KB · ~2.8k tok Raw History
1
/**
2
 * What a drawing is made of: the ask Claude is given, the reply read back
3
 * into SVGs, and the wall every SVG passes before it is kept. Pure
4
 * functions, no I/O — `src/draw.ts` runs Claude, `src/actions.ts` keeps
5
 * the rows.
6
 *
7
 * Every SVG is drawn in three placeholder colours, INK, GLOW and PAPER. A
8
 * palette swaps ink and glow for its own two and paper for its ground, so
9
 * one drawing reads in any theme; tone between them comes from opacity and
10
 * local gradients, never a fourth colour.
11
 * The colours themselves are data: `design/palettes.json`.
12
 */
13
14
import colours from "../design/palettes.json";
15
16
export const KINDS = {
17
  mark: "logo mark",
18
  icon: "app icon",
19
  badge: "badge",
20
  spot: "spot illustration",
21
} as const;
22
export type Kind = keyof typeof KINDS;
23
export const isKind = (value: unknown): value is Kind =>
24
  typeof value === "string" && Object.hasOwn(KINDS, value);
25
26
/** The placeholder colours every SVG is drawn in. */
27
export const INK: string = colours.placeholder.ink;
28
export const GLOW: string = colours.placeholder.glow;
29
/** The ground's colour, for highlights and cut-outs drawn on top. */
30
export const PAPER: string = colours.placeholder.paper;
31
32
/** Palettes a drawing can be shown and saved in. */
33
export const PALETTES: Readonly<
34
  Record<string, { label: string; ink: string; glow: string; ground: string }>
35
> = colours.palettes;
36
export type Palette = keyof typeof colours.palettes;
37
export const isPalette = (value: unknown): value is Palette =>
38
  typeof value === "string" && Object.hasOwn(PALETTES, value);
39
40
export const COUNT = 4;
41
export const PROMPT_MAX = 400;
42
/** The most a kept SVG may weigh, in characters. */
43
export const SVG_MAX = 48_000;
44
45
/** What Claude is asked, for one prompt. */
46
export function ask(prompt: string, kind: Kind): string {
47
  return `You are a senior identity designer who crafts polished, detailed vector marks — the finish of a studio logo, not clip art. Draw ${COUNT} distinct ${KINDS[kind]} concepts for this brief:
48
49
${prompt}
50
51
Rules for every SVG:
52
- Root element exactly: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
53
- First child: <title> with a two-to-four word name for the concept.
54
- Colours: ONLY ${INK} (main ink), ${GLOW} (accent glow) and ${PAPER} (paper — the background colour, for highlights, cut-outs and inner detail drawn on top), plus "none". Write them as hex in fill, stroke and stop-color. No other colours, no colour functions, no CSS, no <style>.
55
- Depth and tone: build shading with linearGradient/radialGradient inside <defs> whose stops use only those colours (fade with stop-opacity), and with fill-opacity/stroke-opacity. Reference them as fill="url(#id)" or stroke="url(#id)"; clipPath works the same way with clip-path="url(#id)". Give every id a short prefix unique to the concept (a1, b1, …).
56
- Allowed elements: svg, title, defs, g, path, circle, ellipse, rect, line, polyline, polygon, linearGradient, radialGradient, stop, clipPath. No text, no images, no filters, no masks, no patterns, no use, no scripts, no links.
57
- Craft: layer several shapes — a confident silhouette, then secondary forms, highlights in paper, a shadow or inner bevel in a darker tone, and fine detail lines in varied stroke weights. Use precise curves (cubic béziers), consistent corner radii and optical balance. Aim for roughly 15–60 shapes, not 3.
58
- It must still read as one clear shape at 32 pixels: the detail rewards a close look, it never muddies the silhouette. Stay inside the viewBox with a margin of about 12.
59
- Make the ${COUNT} concepts genuinely different ideas, not variations of one.
60
61
Reply with exactly ${COUNT} fenced code blocks marked svg, one per concept, and nothing else.`;
62
}
63
64
/** The SVGs in Claude's reply: each fenced block, through the wall; the ones that do not pass are dropped. */
65
export function parseReply(reply: string): string[] {
66
  const blocks = [...reply.matchAll(/```(?:svg|xml)?\s*\n([\s\S]*?)```/g)].map(
67
    (m) => m[1] ?? "",
68
  );
69
  const found =
70
    blocks.length > 0 ? blocks : [...reply.matchAll(/<svg[\s\S]*?<\/svg>/g)].map((m) => m[0]);
71
  return found
72
    .map((svg) => sanitize(svg))
73
    .filter((svg): svg is string => svg !== undefined)
74
    .slice(0, COUNT);
75
}
76
77
// The wall. An SVG is rebuilt from what is allowed, never filtered from what is
78
// not: an element or attribute missing from these lists does not survive, so a
79
// trick nobody thought of has nothing to ride in on.
80
const ELEMENTS = new Set([
81
  "svg", "g", "path", "circle", "ellipse", "rect", "line", "polyline", "polygon", "title",
82
  "defs", "linearGradient", "radialGradient", "stop", "clipPath",
83
]);
84
const ATTRIBUTES = new Set([
85
  "viewBox", "d", "cx", "cy", "r", "rx", "ry", "x", "y", "x1", "y1", "x2", "y2",
86
  "width", "height", "points", "fill", "stroke", "stroke-width", "stroke-linecap",
87
  "stroke-linejoin", "stroke-miterlimit", "stroke-dasharray", "stroke-dashoffset",
88
  "fill-rule", "clip-rule", "opacity", "fill-opacity", "stroke-opacity", "transform",
89
  "id", "offset", "stop-color", "stop-opacity", "gradientUnits", "gradientTransform",
90
  "spreadMethod", "fx", "fy", "fr", "clip-path", "clipPathUnits",
91
]);
92
/** Attributes that may point at a paint or clip in the same SVG — `url(#id)` and nothing else. */
93
const REFERENCES = new Set(["fill", "stroke", "clip-path"]);
94
const LOCAL = /^url\(#[A-Za-z][\w-]*\)$/;
95
const TRANSFORM = /^(\s*(matrix|translate|scale|rotate|skewX|skewY)\([-\d.,\s]*\)\s*)+$/;
96
/** A value: numbers, path data, a colour keyword or hex — never markup; a function only as a transform or a local url. */
97
const VALUE = /^[-\w\s.,#%()]*$/;
98
99
/** Text as text: a bare & is escaped, an entity already written stays one (entities are inert). */
100
const escapeText = (s: string): string =>
101
  s
102
    .replace(/&(?!(?:amp|lt|gt|quot|apos|#\d+|#x[0-9a-f]+);)/gi, "&amp;")
103
    .replace(/</g, "&lt;")
104
    .replace(/>/g, "&gt;");
105
106
/** The SVG rebuilt from what is allowed, or undefined when there is no SVG worth keeping. */
107
export function sanitize(input: string): string | undefined {
108
  if (input.length > SVG_MAX * 2) return undefined;
109
  // Comments, CDATA, doctypes and processing instructions go before reading tags.
110
  const source = input
111
    .replace(/<!--[\s\S]*?-->/g, "")
112
    .replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, "")
113
    .replace(/<![^>]*>/g, "")
114
    .replace(/<\?[\s\S]*?\?>/g, "");
115
  const out: string[] = [];
116
  const open: string[] = [];
117
  let skipping = 0; // depth inside an element that is dropped with its content
118
  let rootSeen = false;
119
  const tag = /<(\/?)([A-Za-z][\w:-]*)((?:\s+[^\s=>\/]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?)*)\s*(\/?)>|([^<]+)|</g;
120
  for (const m of source.matchAll(tag)) {
121
    const [, closing, rawName, attrs = "", selfClosing, text] = m;
122
    if (text !== undefined || rawName === undefined) {
123
      // Text is kept only inside a title; anything else between tags is whitespace or noise.
124
      if (skipping === 0 && open.at(-1) === "title" && text !== undefined)
125
        out.push(escapeText(text));
126
      continue;
127
    }
128
    const name = rawName;
129
    if (closing === "/") {
130
      if (skipping > 0) {
131
        skipping--;
132
        continue;
133
      }
134
      if (open.at(-1) === name) {
135
        open.pop();
136
        out.push(`</${name}>`);
137
        if (name === "svg" && open.length === 0) break;
138
      }
139
      continue;
140
    }
141
    const allowed = ELEMENTS.has(name) && (name === "svg" ? !rootSeen : rootSeen && open.length > 0);
142
    if (!allowed || skipping > 0) {
143
      if (selfClosing !== "/") skipping++;
144
      continue;
145
    }
146
    if (name === "svg") rootSeen = true;
147
    const kept: string[] = name === "svg" ? [`xmlns="http://www.w3.org/2000/svg"`] : [];
148
    for (const a of attrs.matchAll(/([^\s=>\/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) {
149
      const key = a[1] ?? "";
150
      const value = a[2] ?? a[3] ?? a[4] ?? "";
151
      if (!ATTRIBUTES.has(key) || !VALUE.test(value) || value.length > 16_000) continue;
152
      const transform = key === "transform" || key === "gradientTransform";
153
      if (/\(/.test(value) && !(transform && TRANSFORM.test(value)) && !(REFERENCES.has(key) && LOCAL.test(value))) continue;
154
      if (key === "id" && !/^[A-Za-z][\w-]*$/.test(value)) continue;
155
      kept.push(`${key}="${value}"`);
156
    }
157
    const head = `<${name}${kept.length ? ` ${kept.join(" ")}` : ""}`;
158
    if (selfClosing === "/") out.push(`${head}/>`);
159
    else {
160
      out.push(`${head}>`);
161
      open.push(name);
162
    }
163
  }
164
  if (!rootSeen) return undefined;
165
  while (open.length > 0) out.push(`</${open.pop()}>`);
166
  const svg = out.join("");
167
  // A drawing has something in it besides its name.
168
  if (!/<(path|circle|ellipse|rect|line|polyline|polygon)\b/.test(svg)) return undefined;
169
  if (!/viewBox=/.test(svg)) return undefined;
170
  return svg.length <= SVG_MAX ? svg : undefined;
171
}
172
173
/** The concept's name, from its <title>. */
174
export function nameOf(svg: string): string {
175
  const title = /<title>([^<]*)<\/title>/.exec(svg)?.[1]?.trim();
176
  return title === undefined || title === "" ? "Untitled" : title.replace(/&amp;/g, "&");
177
}
178
179
/** The SVG in a palette: INK and GLOW swapped for the palette's two, PAPER for its ground. */
180
export function inPalette(svg: string, palette: Palette): string {
181
  const { ink, glow, ground } = PALETTES[palette]!;
182
  // Every placeholder is marked before any is swapped, so a palette whose colour is another placeholder is not swapped twice.
183
  return svg
184
    .replace(new RegExp(INK, "gi"), "\u0000ink")
185
    .replace(new RegExp(GLOW, "gi"), "\u0000glow")
186
    .replace(new RegExp(PAPER, "gi"), "\u0000paper")
187
    .replace(/\u0000ink/g, ink)
188
    .replace(/\u0000glow/g, glow)
189
    .replace(/\u0000paper/g, ground);
190
}
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts