Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

2.3 KB
Raw Blame
// The browser twin of comment_syntax.py's assembly. index.mjs (generated by
// train.py from the language modules) hands its language list here, and this turns it
// into the syntaxFor() lookup the scanner uses and the sorted MENU the page renders.
// This file is hand-written infrastructure, not a language module.

// The shared no-op line-comment guard. Most languages' prefixes always open a comment;
// only the few with an exception (Perl #, shell #, PHP #) ship their own guard.
export const always = () => true;

// Matches Python os.path.splitext for a POSIX path: the extension including its dot, or
// '' when the basename has no interior dot.
function splitext(p) {
  const sep = p.lastIndexOf('/'), dot = p.lastIndexOf('.');
  if (dot > sep) { for (let i = sep + 1; i < dot; i++) if (p[i] !== '.') return p.slice(dot); }
  return '';
}

// Turn the language list into { syntaxFor, MENU }. `defaultName` names the fallback
// language (its syntax is used for an unknown extension); `selectedExt` is the menu
// entry the dropdown starts on.
export function assemble(languages, defaultName, selectedExt) {
  // Order each delimiter list longest-first, once, so the scanner matches the longest
  // delimiter at a position without re-sorting on every call.
  const byLength = (a, b) => b[0].length - a[0].length;
  for (const L of languages)
    for (const key of ['line', 'block', 'strings', 'docstrings']) L.syntax[key].sort(byLength);

  const byExt = {};
  for (const L of languages) for (const e of L.extensions) byExt[e] = L.syntax;
  const fallback = languages.find(L => L.name === defaultName);
  if (!fallback) throw new Error(`default language ${defaultName} not among the modules`);
  const dflt = fallback.syntax;

  const syntaxFor = hint => {
    const ext = (splitext(hint) || hint).toLowerCase().replace(/^\.+/, '');
    return byExt[ext] || dflt;
  };

  // Every language's menu entries, sorted case-insensitively by label (so the dropdown
  // reads C, C#, C++, Emacs Lisp, Go ... regardless of module order).
  const key = m => m.label.toLowerCase();
  const MENU = languages
    .flatMap(L => L.menu.map(m => ({ label: m.label, ext: m.ext, selected: m.ext === selectedExt })))
    .sort((a, b) => key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0);

  return { syntaxFor, MENU };
}