Home / Function/ RLSCodeEditor() — supabase Function Reference

RLSCodeEditor() — supabase Function Reference

Architecture documentation for the RLSCodeEditor() function in RLSCodeEditor.tsx from the supabase codebase.

Entity Profile

Relationship Graph

Source Code

apps/studio/components/interfaces/Auth/Policies/PolicyEditorPanel/RLSCodeEditor.tsx lines 33–183

export const RLSCodeEditor = ({
  id,
  defaultValue,
  wrapperClassName,
  className,
  value,
  placeholder,
  readOnly = false,

  disableTabToUsePlaceholder = false,
  lineNumberStart,
  onChange = noop,
  onMount: _onMount = noop,

  editorRef,
  monacoRef,
}: RLSCodeEditorProps) => {
  const hasValue = useRef<any>()
  const monaco = useMonaco()

  const placeholderId = `monaco-placeholder-${id}`
  const options: editor.IStandaloneEditorConstructionOptions = {
    tabSize: 2,
    fontSize: 13,
    readOnly,
    minimap: { enabled: false },
    wordWrap: 'on' as const,
    contextmenu: true,
    lineNumbers:
      lineNumberStart !== undefined ? (num) => (num + lineNumberStart).toString() : undefined,
    glyphMargin: undefined,
    lineNumbersMinChars: 4,
    folding: undefined,
    scrollBeyondLastLine: false,
  }

  const onMount: OnMount = async (editor, monaco) => {
    editorRef.current = editor
    if (monacoRef !== undefined) monacoRef.current = monaco

    hasValue.current = editor.createContextKey('hasValue', false)
    const placeholderEl = document.getElementById(placeholderId) as HTMLElement | null
    if (placeholderEl && placeholder !== undefined && (value ?? '').trim().length === 0) {
      placeholderEl.style.display = 'block'
    }

    if (!disableTabToUsePlaceholder) {
      editor.addCommand(
        monaco.KeyCode.Tab,
        () => {
          editor.executeEdits('source', [
            {
              // @ts-ignore
              identifier: 'add-placeholder',
              range: new monaco.Range(1, 1, 1, 1),
              text: (placeholder ?? '')
                .split('\n\n')
                .join('\n')
                .replaceAll('*', '')
                .replaceAll('&nbsp;', ''),
            },
          ])
        },
        '!hasValue'
      )
    }

    editor.focus()

    _onMount()
  }

  const onChangeContent: OnChange = (value) => {
    hasValue.current.set((value ?? '').length > 0)

    const placeholderEl = document.getElementById(placeholderId) as HTMLElement | null
    if (placeholderEl) {
      if (!value) {
        placeholderEl.style.display = 'block'
      } else {
        placeholderEl.style.display = 'none'
      }
    }

    onChange()
  }

  // when the value has changed, trigger the onChange callback so that the height of the container can be adjusted.
  // Happens when the value wordwraps and is updated via a template.
  useEffect(() => {
    onChange()
  }, [value])

  useEffect(() => {
    if (monaco) {
      // Enable pgsql format
      const formatprovider = monaco.languages.registerDocumentFormattingEditProvider('pgsql', {
        async provideDocumentFormattingEdits(model: any) {
          const value = model.getValue()
          const formatted = formatSql(value)
          return [
            {
              range: model.getFullModelRange(),
              text: formatted.trim(),
            },
          ]
        },
      })

      return () => {
        formatprovider.dispose()
      }
    }
  }, [monaco])

  useEffect(() => {
    if (value !== undefined && value.trim().length > 0) {
      const placeholderEl = document.getElementById(placeholderId) as HTMLElement | null
      if (placeholderEl) placeholderEl.style.display = 'none'
    }
  }, [value])

  return (
    <>
      <Editor
        path={id}
        theme="supabase"
        wrapperProps={{ className: cn(wrapperClassName) }}
        className={cn(className, 'monaco-editor')}
        value={value ?? undefined}
        defaultLanguage="pgsql"
        defaultValue={defaultValue ?? undefined}
        options={options}
        onMount={onMount}
        onChange={onChangeContent}
      />
      {placeholder !== undefined && (
        <div
          id={placeholderId}
          className={cn(
            'monaco-placeholder absolute top-[0px] left-[57px] text-sm pointer-events-none font-mono tracking-tighter',
            '[&>div>p]:text-foreground-lighter [&>div>p]:!m-0'
          )}
          style={{ display: 'none' }}
        >
          <Markdown content={placeholder} />
        </div>
      )}
    </>
  )
}

Subdomains

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free