compiler-dom.esm-bundler.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import { registerRuntimeHelpers, isBuiltInType, createSimpleExpression, createCompilerError, createObjectProperty, getConstantType, createCallExpression, TO_DISPLAY_STRING, transformModel as transformModel$1, findProp, hasDynamicKeyVBind, transformOn as transformOn$1, createCompoundExpression, isStaticExp, checkCompatEnabled, noopDirectiveTransform, baseCompile, baseParse } from '@vue/compiler-core';
  2. export * from '@vue/compiler-core';
  3. import { isVoidTag, isHTMLTag, isSVGTag, makeMap, parseStringStyle, capitalize, extend } from '@vue/shared';
  4. const V_MODEL_RADIO = Symbol((process.env.NODE_ENV !== 'production') ? `vModelRadio` : ``);
  5. const V_MODEL_CHECKBOX = Symbol((process.env.NODE_ENV !== 'production') ? `vModelCheckbox` : ``);
  6. const V_MODEL_TEXT = Symbol((process.env.NODE_ENV !== 'production') ? `vModelText` : ``);
  7. const V_MODEL_SELECT = Symbol((process.env.NODE_ENV !== 'production') ? `vModelSelect` : ``);
  8. const V_MODEL_DYNAMIC = Symbol((process.env.NODE_ENV !== 'production') ? `vModelDynamic` : ``);
  9. const V_ON_WITH_MODIFIERS = Symbol((process.env.NODE_ENV !== 'production') ? `vOnModifiersGuard` : ``);
  10. const V_ON_WITH_KEYS = Symbol((process.env.NODE_ENV !== 'production') ? `vOnKeysGuard` : ``);
  11. const V_SHOW = Symbol((process.env.NODE_ENV !== 'production') ? `vShow` : ``);
  12. const TRANSITION = Symbol((process.env.NODE_ENV !== 'production') ? `Transition` : ``);
  13. const TRANSITION_GROUP = Symbol((process.env.NODE_ENV !== 'production') ? `TransitionGroup` : ``);
  14. registerRuntimeHelpers({
  15. [V_MODEL_RADIO]: `vModelRadio`,
  16. [V_MODEL_CHECKBOX]: `vModelCheckbox`,
  17. [V_MODEL_TEXT]: `vModelText`,
  18. [V_MODEL_SELECT]: `vModelSelect`,
  19. [V_MODEL_DYNAMIC]: `vModelDynamic`,
  20. [V_ON_WITH_MODIFIERS]: `withModifiers`,
  21. [V_ON_WITH_KEYS]: `withKeys`,
  22. [V_SHOW]: `vShow`,
  23. [TRANSITION]: `Transition`,
  24. [TRANSITION_GROUP]: `TransitionGroup`
  25. });
  26. /* eslint-disable no-restricted-globals */
  27. let decoder;
  28. function decodeHtmlBrowser(raw, asAttr = false) {
  29. if (!decoder) {
  30. decoder = document.createElement('div');
  31. }
  32. if (asAttr) {
  33. decoder.innerHTML = `<div foo="${raw.replace(/"/g, '&quot;')}">`;
  34. return decoder.children[0].getAttribute('foo');
  35. }
  36. else {
  37. decoder.innerHTML = raw;
  38. return decoder.textContent;
  39. }
  40. }
  41. const isRawTextContainer = /*#__PURE__*/ makeMap('style,iframe,script,noscript', true);
  42. const parserOptions = {
  43. isVoidTag,
  44. isNativeTag: tag => isHTMLTag(tag) || isSVGTag(tag),
  45. isPreTag: tag => tag === 'pre',
  46. decodeEntities: decodeHtmlBrowser ,
  47. isBuiltInComponent: (tag) => {
  48. if (isBuiltInType(tag, `Transition`)) {
  49. return TRANSITION;
  50. }
  51. else if (isBuiltInType(tag, `TransitionGroup`)) {
  52. return TRANSITION_GROUP;
  53. }
  54. },
  55. // https://html.spec.whatwg.org/multipage/parsing.html#tree-construction-dispatcher
  56. getNamespace(tag, parent) {
  57. let ns = parent ? parent.ns : 0 /* DOMNamespaces.HTML */;
  58. if (parent && ns === 2 /* DOMNamespaces.MATH_ML */) {
  59. if (parent.tag === 'annotation-xml') {
  60. if (tag === 'svg') {
  61. return 1 /* DOMNamespaces.SVG */;
  62. }
  63. if (parent.props.some(a => a.type === 6 /* NodeTypes.ATTRIBUTE */ &&
  64. a.name === 'encoding' &&
  65. a.value != null &&
  66. (a.value.content === 'text/html' ||
  67. a.value.content === 'application/xhtml+xml'))) {
  68. ns = 0 /* DOMNamespaces.HTML */;
  69. }
  70. }
  71. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  72. tag !== 'mglyph' &&
  73. tag !== 'malignmark') {
  74. ns = 0 /* DOMNamespaces.HTML */;
  75. }
  76. }
  77. else if (parent && ns === 1 /* DOMNamespaces.SVG */) {
  78. if (parent.tag === 'foreignObject' ||
  79. parent.tag === 'desc' ||
  80. parent.tag === 'title') {
  81. ns = 0 /* DOMNamespaces.HTML */;
  82. }
  83. }
  84. if (ns === 0 /* DOMNamespaces.HTML */) {
  85. if (tag === 'svg') {
  86. return 1 /* DOMNamespaces.SVG */;
  87. }
  88. if (tag === 'math') {
  89. return 2 /* DOMNamespaces.MATH_ML */;
  90. }
  91. }
  92. return ns;
  93. },
  94. // https://html.spec.whatwg.org/multipage/parsing.html#parsing-html-fragments
  95. getTextMode({ tag, ns }) {
  96. if (ns === 0 /* DOMNamespaces.HTML */) {
  97. if (tag === 'textarea' || tag === 'title') {
  98. return 1 /* TextModes.RCDATA */;
  99. }
  100. if (isRawTextContainer(tag)) {
  101. return 2 /* TextModes.RAWTEXT */;
  102. }
  103. }
  104. return 0 /* TextModes.DATA */;
  105. }
  106. };
  107. // Parse inline CSS strings for static style attributes into an object.
  108. // This is a NodeTransform since it works on the static `style` attribute and
  109. // converts it into a dynamic equivalent:
  110. // style="color: red" -> :style='{ "color": "red" }'
  111. // It is then processed by `transformElement` and included in the generated
  112. // props.
  113. const transformStyle = node => {
  114. if (node.type === 1 /* NodeTypes.ELEMENT */) {
  115. node.props.forEach((p, i) => {
  116. if (p.type === 6 /* NodeTypes.ATTRIBUTE */ && p.name === 'style' && p.value) {
  117. // replace p with an expression node
  118. node.props[i] = {
  119. type: 7 /* NodeTypes.DIRECTIVE */,
  120. name: `bind`,
  121. arg: createSimpleExpression(`style`, true, p.loc),
  122. exp: parseInlineCSS(p.value.content, p.loc),
  123. modifiers: [],
  124. loc: p.loc
  125. };
  126. }
  127. });
  128. }
  129. };
  130. const parseInlineCSS = (cssText, loc) => {
  131. const normalized = parseStringStyle(cssText);
  132. return createSimpleExpression(JSON.stringify(normalized), false, loc, 3 /* ConstantTypes.CAN_STRINGIFY */);
  133. };
  134. function createDOMCompilerError(code, loc) {
  135. return createCompilerError(code, loc, (process.env.NODE_ENV !== 'production') || !true ? DOMErrorMessages : undefined);
  136. }
  137. const DOMErrorMessages = {
  138. [51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  139. [52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  140. [53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  141. [54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  142. [55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  143. [56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  144. [57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */]: `v-model cannot be used on file inputs since they are read-only. Use a v-on:change listener instead.`,
  145. [58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  146. [59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  147. [60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  148. [61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */]: `Tags with side effect (<script> and <style>) are ignored in client component templates.`
  149. };
  150. const transformVHtml = (dir, node, context) => {
  151. const { exp, loc } = dir;
  152. if (!exp) {
  153. context.onError(createDOMCompilerError(51 /* DOMErrorCodes.X_V_HTML_NO_EXPRESSION */, loc));
  154. }
  155. if (node.children.length) {
  156. context.onError(createDOMCompilerError(52 /* DOMErrorCodes.X_V_HTML_WITH_CHILDREN */, loc));
  157. node.children.length = 0;
  158. }
  159. return {
  160. props: [
  161. createObjectProperty(createSimpleExpression(`innerHTML`, true, loc), exp || createSimpleExpression('', true))
  162. ]
  163. };
  164. };
  165. const transformVText = (dir, node, context) => {
  166. const { exp, loc } = dir;
  167. if (!exp) {
  168. context.onError(createDOMCompilerError(53 /* DOMErrorCodes.X_V_TEXT_NO_EXPRESSION */, loc));
  169. }
  170. if (node.children.length) {
  171. context.onError(createDOMCompilerError(54 /* DOMErrorCodes.X_V_TEXT_WITH_CHILDREN */, loc));
  172. node.children.length = 0;
  173. }
  174. return {
  175. props: [
  176. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  177. ? getConstantType(exp, context) > 0
  178. ? exp
  179. : createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  180. : createSimpleExpression('', true))
  181. ]
  182. };
  183. };
  184. const transformModel = (dir, node, context) => {
  185. const baseResult = transformModel$1(dir, node, context);
  186. // base transform has errors OR component v-model (only need props)
  187. if (!baseResult.props.length || node.tagType === 1 /* ElementTypes.COMPONENT */) {
  188. return baseResult;
  189. }
  190. if (dir.arg) {
  191. context.onError(createDOMCompilerError(56 /* DOMErrorCodes.X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  192. }
  193. function checkDuplicatedValue() {
  194. const value = findProp(node, 'value');
  195. if (value) {
  196. context.onError(createDOMCompilerError(58 /* DOMErrorCodes.X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  197. }
  198. }
  199. const { tag } = node;
  200. const isCustomElement = context.isCustomElement(tag);
  201. if (tag === 'input' ||
  202. tag === 'textarea' ||
  203. tag === 'select' ||
  204. isCustomElement) {
  205. let directiveToUse = V_MODEL_TEXT;
  206. let isInvalidType = false;
  207. if (tag === 'input' || isCustomElement) {
  208. const type = findProp(node, `type`);
  209. if (type) {
  210. if (type.type === 7 /* NodeTypes.DIRECTIVE */) {
  211. // :type="foo"
  212. directiveToUse = V_MODEL_DYNAMIC;
  213. }
  214. else if (type.value) {
  215. switch (type.value.content) {
  216. case 'radio':
  217. directiveToUse = V_MODEL_RADIO;
  218. break;
  219. case 'checkbox':
  220. directiveToUse = V_MODEL_CHECKBOX;
  221. break;
  222. case 'file':
  223. isInvalidType = true;
  224. context.onError(createDOMCompilerError(57 /* DOMErrorCodes.X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  225. break;
  226. default:
  227. // text type
  228. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  229. break;
  230. }
  231. }
  232. }
  233. else if (hasDynamicKeyVBind(node)) {
  234. // element has bindings with dynamic keys, which can possibly contain
  235. // "type".
  236. directiveToUse = V_MODEL_DYNAMIC;
  237. }
  238. else {
  239. // text type
  240. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  241. }
  242. }
  243. else if (tag === 'select') {
  244. directiveToUse = V_MODEL_SELECT;
  245. }
  246. else {
  247. // textarea
  248. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  249. }
  250. // inject runtime directive
  251. // by returning the helper symbol via needRuntime
  252. // the import will replaced a resolveDirective call.
  253. if (!isInvalidType) {
  254. baseResult.needRuntime = context.helper(directiveToUse);
  255. }
  256. }
  257. else {
  258. context.onError(createDOMCompilerError(55 /* DOMErrorCodes.X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  259. }
  260. // native vmodel doesn't need the `modelValue` props since they are also
  261. // passed to the runtime as `binding.value`. removing it reduces code size.
  262. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* NodeTypes.SIMPLE_EXPRESSION */ &&
  263. p.key.content === 'modelValue'));
  264. return baseResult;
  265. };
  266. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  267. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  268. // event propagation management
  269. `stop,prevent,self,` +
  270. // system modifiers + exact
  271. `ctrl,shift,alt,meta,exact,` +
  272. // mouse
  273. `middle`);
  274. // left & right could be mouse or key modifiers based on event type
  275. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  276. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  277. const resolveModifiers = (key, modifiers, context, loc) => {
  278. const keyModifiers = [];
  279. const nonKeyModifiers = [];
  280. const eventOptionModifiers = [];
  281. for (let i = 0; i < modifiers.length; i++) {
  282. const modifier = modifiers[i];
  283. if (modifier === 'native' &&
  284. checkCompatEnabled("COMPILER_V_ON_NATIVE" /* CompilerDeprecationTypes.COMPILER_V_ON_NATIVE */, context, loc)) {
  285. eventOptionModifiers.push(modifier);
  286. }
  287. else if (isEventOptionModifier(modifier)) {
  288. // eventOptionModifiers: modifiers for addEventListener() options,
  289. // e.g. .passive & .capture
  290. eventOptionModifiers.push(modifier);
  291. }
  292. else {
  293. // runtimeModifiers: modifiers that needs runtime guards
  294. if (maybeKeyModifier(modifier)) {
  295. if (isStaticExp(key)) {
  296. if (isKeyboardEvent(key.content)) {
  297. keyModifiers.push(modifier);
  298. }
  299. else {
  300. nonKeyModifiers.push(modifier);
  301. }
  302. }
  303. else {
  304. keyModifiers.push(modifier);
  305. nonKeyModifiers.push(modifier);
  306. }
  307. }
  308. else {
  309. if (isNonKeyModifier(modifier)) {
  310. nonKeyModifiers.push(modifier);
  311. }
  312. else {
  313. keyModifiers.push(modifier);
  314. }
  315. }
  316. }
  317. }
  318. return {
  319. keyModifiers,
  320. nonKeyModifiers,
  321. eventOptionModifiers
  322. };
  323. };
  324. const transformClick = (key, event) => {
  325. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  326. return isStaticClick
  327. ? createSimpleExpression(event, true)
  328. : key.type !== 4 /* NodeTypes.SIMPLE_EXPRESSION */
  329. ? createCompoundExpression([
  330. `(`,
  331. key,
  332. `) === "onClick" ? "${event}" : (`,
  333. key,
  334. `)`
  335. ])
  336. : key;
  337. };
  338. const transformOn = (dir, node, context) => {
  339. return transformOn$1(dir, node, context, baseResult => {
  340. const { modifiers } = dir;
  341. if (!modifiers.length)
  342. return baseResult;
  343. let { key, value: handlerExp } = baseResult.props[0];
  344. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  345. // normalize click.right and click.middle since they don't actually fire
  346. if (nonKeyModifiers.includes('right')) {
  347. key = transformClick(key, `onContextmenu`);
  348. }
  349. if (nonKeyModifiers.includes('middle')) {
  350. key = transformClick(key, `onMouseup`);
  351. }
  352. if (nonKeyModifiers.length) {
  353. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  354. handlerExp,
  355. JSON.stringify(nonKeyModifiers)
  356. ]);
  357. }
  358. if (keyModifiers.length &&
  359. // if event name is dynamic, always wrap with keys guard
  360. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  361. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  362. handlerExp,
  363. JSON.stringify(keyModifiers)
  364. ]);
  365. }
  366. if (eventOptionModifiers.length) {
  367. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  368. key = isStaticExp(key)
  369. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  370. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  371. }
  372. return {
  373. props: [createObjectProperty(key, handlerExp)]
  374. };
  375. });
  376. };
  377. const transformShow = (dir, node, context) => {
  378. const { exp, loc } = dir;
  379. if (!exp) {
  380. context.onError(createDOMCompilerError(59 /* DOMErrorCodes.X_V_SHOW_NO_EXPRESSION */, loc));
  381. }
  382. return {
  383. props: [],
  384. needRuntime: context.helper(V_SHOW)
  385. };
  386. };
  387. const transformTransition = (node, context) => {
  388. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  389. node.tagType === 1 /* ElementTypes.COMPONENT */) {
  390. const component = context.isBuiltInComponent(node.tag);
  391. if (component === TRANSITION) {
  392. return () => {
  393. if (!node.children.length) {
  394. return;
  395. }
  396. // warn multiple transition children
  397. if (hasMultipleChildren(node)) {
  398. context.onError(createDOMCompilerError(60 /* DOMErrorCodes.X_TRANSITION_INVALID_CHILDREN */, {
  399. start: node.children[0].loc.start,
  400. end: node.children[node.children.length - 1].loc.end,
  401. source: ''
  402. }));
  403. }
  404. // check if it's s single child w/ v-show
  405. // if yes, inject "persisted: true" to the transition props
  406. const child = node.children[0];
  407. if (child.type === 1 /* NodeTypes.ELEMENT */) {
  408. for (const p of child.props) {
  409. if (p.type === 7 /* NodeTypes.DIRECTIVE */ && p.name === 'show') {
  410. node.props.push({
  411. type: 6 /* NodeTypes.ATTRIBUTE */,
  412. name: 'persisted',
  413. value: undefined,
  414. loc: node.loc
  415. });
  416. }
  417. }
  418. }
  419. };
  420. }
  421. }
  422. };
  423. function hasMultipleChildren(node) {
  424. // #1352 filter out potential comment nodes.
  425. const children = (node.children = node.children.filter(c => c.type !== 3 /* NodeTypes.COMMENT */ &&
  426. !(c.type === 2 /* NodeTypes.TEXT */ && !c.content.trim())));
  427. const child = children[0];
  428. return (children.length !== 1 ||
  429. child.type === 11 /* NodeTypes.FOR */ ||
  430. (child.type === 9 /* NodeTypes.IF */ && child.branches.some(hasMultipleChildren)));
  431. }
  432. const ignoreSideEffectTags = (node, context) => {
  433. if (node.type === 1 /* NodeTypes.ELEMENT */ &&
  434. node.tagType === 0 /* ElementTypes.ELEMENT */ &&
  435. (node.tag === 'script' || node.tag === 'style')) {
  436. context.onError(createDOMCompilerError(61 /* DOMErrorCodes.X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  437. context.removeNode();
  438. }
  439. };
  440. const DOMNodeTransforms = [
  441. transformStyle,
  442. ...((process.env.NODE_ENV !== 'production') ? [transformTransition] : [])
  443. ];
  444. const DOMDirectiveTransforms = {
  445. cloak: noopDirectiveTransform,
  446. html: transformVHtml,
  447. text: transformVText,
  448. model: transformModel,
  449. on: transformOn,
  450. show: transformShow
  451. };
  452. function compile(template, options = {}) {
  453. return baseCompile(template, extend({}, parserOptions, options, {
  454. nodeTransforms: [
  455. // ignore <script> and <tag>
  456. // this is not put inside DOMNodeTransforms because that list is used
  457. // by compiler-ssr to generate vnode fallback branches
  458. ignoreSideEffectTags,
  459. ...DOMNodeTransforms,
  460. ...(options.nodeTransforms || [])
  461. ],
  462. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  463. transformHoist: null
  464. }));
  465. }
  466. function parse(template, options = {}) {
  467. return baseParse(template, extend({}, parserOptions, options));
  468. }
  469. export { DOMDirectiveTransforms, DOMNodeTransforms, TRANSITION, TRANSITION_GROUP, V_MODEL_CHECKBOX, V_MODEL_DYNAMIC, V_MODEL_RADIO, V_MODEL_SELECT, V_MODEL_TEXT, V_ON_WITH_KEYS, V_ON_WITH_MODIFIERS, V_SHOW, compile, createDOMCompilerError, parse, parserOptions, transformStyle };