compiler-dom.esm-bundler.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. import { registerRuntimeHelpers, isBuiltInType, createSimpleExpression, createCompilerError, createObjectProperty, 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 /* HTML */;
  58. if (parent && ns === 2 /* MATH_ML */) {
  59. if (parent.tag === 'annotation-xml') {
  60. if (tag === 'svg') {
  61. return 1 /* SVG */;
  62. }
  63. if (parent.props.some(a => a.type === 6 /* 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 /* HTML */;
  69. }
  70. }
  71. else if (/^m(?:[ions]|text)$/.test(parent.tag) &&
  72. tag !== 'mglyph' &&
  73. tag !== 'malignmark') {
  74. ns = 0 /* HTML */;
  75. }
  76. }
  77. else if (parent && ns === 1 /* SVG */) {
  78. if (parent.tag === 'foreignObject' ||
  79. parent.tag === 'desc' ||
  80. parent.tag === 'title') {
  81. ns = 0 /* HTML */;
  82. }
  83. }
  84. if (ns === 0 /* HTML */) {
  85. if (tag === 'svg') {
  86. return 1 /* SVG */;
  87. }
  88. if (tag === 'math') {
  89. return 2 /* 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 /* HTML */) {
  97. if (tag === 'textarea' || tag === 'title') {
  98. return 1 /* RCDATA */;
  99. }
  100. if (isRawTextContainer(tag)) {
  101. return 2 /* RAWTEXT */;
  102. }
  103. }
  104. return 0 /* 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 /* ELEMENT */) {
  115. node.props.forEach((p, i) => {
  116. if (p.type === 6 /* ATTRIBUTE */ && p.name === 'style' && p.value) {
  117. // replace p with an expression node
  118. node.props[i] = {
  119. type: 7 /* 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 /* 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. [50 /* X_V_HTML_NO_EXPRESSION */]: `v-html is missing expression.`,
  139. [51 /* X_V_HTML_WITH_CHILDREN */]: `v-html will override element children.`,
  140. [52 /* X_V_TEXT_NO_EXPRESSION */]: `v-text is missing expression.`,
  141. [53 /* X_V_TEXT_WITH_CHILDREN */]: `v-text will override element children.`,
  142. [54 /* X_V_MODEL_ON_INVALID_ELEMENT */]: `v-model can only be used on <input>, <textarea> and <select> elements.`,
  143. [55 /* X_V_MODEL_ARG_ON_ELEMENT */]: `v-model argument is not supported on plain elements.`,
  144. [56 /* 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. [57 /* X_V_MODEL_UNNECESSARY_VALUE */]: `Unnecessary value binding used alongside v-model. It will interfere with v-model's behavior.`,
  146. [58 /* X_V_SHOW_NO_EXPRESSION */]: `v-show is missing expression.`,
  147. [59 /* X_TRANSITION_INVALID_CHILDREN */]: `<Transition> expects exactly one child element or component.`,
  148. [60 /* 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(50 /* X_V_HTML_NO_EXPRESSION */, loc));
  154. }
  155. if (node.children.length) {
  156. context.onError(createDOMCompilerError(51 /* 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(52 /* X_V_TEXT_NO_EXPRESSION */, loc));
  169. }
  170. if (node.children.length) {
  171. context.onError(createDOMCompilerError(53 /* X_V_TEXT_WITH_CHILDREN */, loc));
  172. node.children.length = 0;
  173. }
  174. return {
  175. props: [
  176. createObjectProperty(createSimpleExpression(`textContent`, true), exp
  177. ? createCallExpression(context.helperString(TO_DISPLAY_STRING), [exp], loc)
  178. : createSimpleExpression('', true))
  179. ]
  180. };
  181. };
  182. const transformModel = (dir, node, context) => {
  183. const baseResult = transformModel$1(dir, node, context);
  184. // base transform has errors OR component v-model (only need props)
  185. if (!baseResult.props.length || node.tagType === 1 /* COMPONENT */) {
  186. return baseResult;
  187. }
  188. if (dir.arg) {
  189. context.onError(createDOMCompilerError(55 /* X_V_MODEL_ARG_ON_ELEMENT */, dir.arg.loc));
  190. }
  191. function checkDuplicatedValue() {
  192. const value = findProp(node, 'value');
  193. if (value) {
  194. context.onError(createDOMCompilerError(57 /* X_V_MODEL_UNNECESSARY_VALUE */, value.loc));
  195. }
  196. }
  197. const { tag } = node;
  198. const isCustomElement = context.isCustomElement(tag);
  199. if (tag === 'input' ||
  200. tag === 'textarea' ||
  201. tag === 'select' ||
  202. isCustomElement) {
  203. let directiveToUse = V_MODEL_TEXT;
  204. let isInvalidType = false;
  205. if (tag === 'input' || isCustomElement) {
  206. const type = findProp(node, `type`);
  207. if (type) {
  208. if (type.type === 7 /* DIRECTIVE */) {
  209. // :type="foo"
  210. directiveToUse = V_MODEL_DYNAMIC;
  211. }
  212. else if (type.value) {
  213. switch (type.value.content) {
  214. case 'radio':
  215. directiveToUse = V_MODEL_RADIO;
  216. break;
  217. case 'checkbox':
  218. directiveToUse = V_MODEL_CHECKBOX;
  219. break;
  220. case 'file':
  221. isInvalidType = true;
  222. context.onError(createDOMCompilerError(56 /* X_V_MODEL_ON_FILE_INPUT_ELEMENT */, dir.loc));
  223. break;
  224. default:
  225. // text type
  226. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  227. break;
  228. }
  229. }
  230. }
  231. else if (hasDynamicKeyVBind(node)) {
  232. // element has bindings with dynamic keys, which can possibly contain
  233. // "type".
  234. directiveToUse = V_MODEL_DYNAMIC;
  235. }
  236. else {
  237. // text type
  238. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  239. }
  240. }
  241. else if (tag === 'select') {
  242. directiveToUse = V_MODEL_SELECT;
  243. }
  244. else {
  245. // textarea
  246. (process.env.NODE_ENV !== 'production') && checkDuplicatedValue();
  247. }
  248. // inject runtime directive
  249. // by returning the helper symbol via needRuntime
  250. // the import will replaced a resolveDirective call.
  251. if (!isInvalidType) {
  252. baseResult.needRuntime = context.helper(directiveToUse);
  253. }
  254. }
  255. else {
  256. context.onError(createDOMCompilerError(54 /* X_V_MODEL_ON_INVALID_ELEMENT */, dir.loc));
  257. }
  258. // native vmodel doesn't need the `modelValue` props since they are also
  259. // passed to the runtime as `binding.value`. removing it reduces code size.
  260. baseResult.props = baseResult.props.filter(p => !(p.key.type === 4 /* SIMPLE_EXPRESSION */ &&
  261. p.key.content === 'modelValue'));
  262. return baseResult;
  263. };
  264. const isEventOptionModifier = /*#__PURE__*/ makeMap(`passive,once,capture`);
  265. const isNonKeyModifier = /*#__PURE__*/ makeMap(
  266. // event propagation management
  267. `stop,prevent,self,` +
  268. // system modifiers + exact
  269. `ctrl,shift,alt,meta,exact,` +
  270. // mouse
  271. `middle`);
  272. // left & right could be mouse or key modifiers based on event type
  273. const maybeKeyModifier = /*#__PURE__*/ makeMap('left,right');
  274. const isKeyboardEvent = /*#__PURE__*/ makeMap(`onkeyup,onkeydown,onkeypress`, true);
  275. const resolveModifiers = (key, modifiers, context, loc) => {
  276. const keyModifiers = [];
  277. const nonKeyModifiers = [];
  278. const eventOptionModifiers = [];
  279. for (let i = 0; i < modifiers.length; i++) {
  280. const modifier = modifiers[i];
  281. if (modifier === 'native' &&
  282. checkCompatEnabled("COMPILER_V_ON_NATIVE" /* COMPILER_V_ON_NATIVE */, context, loc)) {
  283. eventOptionModifiers.push(modifier);
  284. }
  285. else if (isEventOptionModifier(modifier)) {
  286. // eventOptionModifiers: modifiers for addEventListener() options,
  287. // e.g. .passive & .capture
  288. eventOptionModifiers.push(modifier);
  289. }
  290. else {
  291. // runtimeModifiers: modifiers that needs runtime guards
  292. if (maybeKeyModifier(modifier)) {
  293. if (isStaticExp(key)) {
  294. if (isKeyboardEvent(key.content)) {
  295. keyModifiers.push(modifier);
  296. }
  297. else {
  298. nonKeyModifiers.push(modifier);
  299. }
  300. }
  301. else {
  302. keyModifiers.push(modifier);
  303. nonKeyModifiers.push(modifier);
  304. }
  305. }
  306. else {
  307. if (isNonKeyModifier(modifier)) {
  308. nonKeyModifiers.push(modifier);
  309. }
  310. else {
  311. keyModifiers.push(modifier);
  312. }
  313. }
  314. }
  315. }
  316. return {
  317. keyModifiers,
  318. nonKeyModifiers,
  319. eventOptionModifiers
  320. };
  321. };
  322. const transformClick = (key, event) => {
  323. const isStaticClick = isStaticExp(key) && key.content.toLowerCase() === 'onclick';
  324. return isStaticClick
  325. ? createSimpleExpression(event, true)
  326. : key.type !== 4 /* SIMPLE_EXPRESSION */
  327. ? createCompoundExpression([
  328. `(`,
  329. key,
  330. `) === "onClick" ? "${event}" : (`,
  331. key,
  332. `)`
  333. ])
  334. : key;
  335. };
  336. const transformOn = (dir, node, context) => {
  337. return transformOn$1(dir, node, context, baseResult => {
  338. const { modifiers } = dir;
  339. if (!modifiers.length)
  340. return baseResult;
  341. let { key, value: handlerExp } = baseResult.props[0];
  342. const { keyModifiers, nonKeyModifiers, eventOptionModifiers } = resolveModifiers(key, modifiers, context, dir.loc);
  343. // normalize click.right and click.middle since they don't actually fire
  344. if (nonKeyModifiers.includes('right')) {
  345. key = transformClick(key, `onContextmenu`);
  346. }
  347. if (nonKeyModifiers.includes('middle')) {
  348. key = transformClick(key, `onMouseup`);
  349. }
  350. if (nonKeyModifiers.length) {
  351. handlerExp = createCallExpression(context.helper(V_ON_WITH_MODIFIERS), [
  352. handlerExp,
  353. JSON.stringify(nonKeyModifiers)
  354. ]);
  355. }
  356. if (keyModifiers.length &&
  357. // if event name is dynamic, always wrap with keys guard
  358. (!isStaticExp(key) || isKeyboardEvent(key.content))) {
  359. handlerExp = createCallExpression(context.helper(V_ON_WITH_KEYS), [
  360. handlerExp,
  361. JSON.stringify(keyModifiers)
  362. ]);
  363. }
  364. if (eventOptionModifiers.length) {
  365. const modifierPostfix = eventOptionModifiers.map(capitalize).join('');
  366. key = isStaticExp(key)
  367. ? createSimpleExpression(`${key.content}${modifierPostfix}`, true)
  368. : createCompoundExpression([`(`, key, `) + "${modifierPostfix}"`]);
  369. }
  370. return {
  371. props: [createObjectProperty(key, handlerExp)]
  372. };
  373. });
  374. };
  375. const transformShow = (dir, node, context) => {
  376. const { exp, loc } = dir;
  377. if (!exp) {
  378. context.onError(createDOMCompilerError(58 /* X_V_SHOW_NO_EXPRESSION */, loc));
  379. }
  380. return {
  381. props: [],
  382. needRuntime: context.helper(V_SHOW)
  383. };
  384. };
  385. const warnTransitionChildren = (node, context) => {
  386. if (node.type === 1 /* ELEMENT */ &&
  387. node.tagType === 1 /* COMPONENT */) {
  388. const component = context.isBuiltInComponent(node.tag);
  389. if (component === TRANSITION) {
  390. return () => {
  391. if (node.children.length && hasMultipleChildren(node)) {
  392. context.onError(createDOMCompilerError(59 /* X_TRANSITION_INVALID_CHILDREN */, {
  393. start: node.children[0].loc.start,
  394. end: node.children[node.children.length - 1].loc.end,
  395. source: ''
  396. }));
  397. }
  398. };
  399. }
  400. }
  401. };
  402. function hasMultipleChildren(node) {
  403. // #1352 filter out potential comment nodes.
  404. const children = (node.children = node.children.filter(c => c.type !== 3 /* COMMENT */));
  405. const child = children[0];
  406. return (children.length !== 1 ||
  407. child.type === 11 /* FOR */ ||
  408. (child.type === 9 /* IF */ && child.branches.some(hasMultipleChildren)));
  409. }
  410. const ignoreSideEffectTags = (node, context) => {
  411. if (node.type === 1 /* ELEMENT */ &&
  412. node.tagType === 0 /* ELEMENT */ &&
  413. (node.tag === 'script' || node.tag === 'style')) {
  414. context.onError(createDOMCompilerError(60 /* X_IGNORED_SIDE_EFFECT_TAG */, node.loc));
  415. context.removeNode();
  416. }
  417. };
  418. const DOMNodeTransforms = [
  419. transformStyle,
  420. ...((process.env.NODE_ENV !== 'production') ? [warnTransitionChildren] : [])
  421. ];
  422. const DOMDirectiveTransforms = {
  423. cloak: noopDirectiveTransform,
  424. html: transformVHtml,
  425. text: transformVText,
  426. model: transformModel,
  427. on: transformOn,
  428. show: transformShow
  429. };
  430. function compile(template, options = {}) {
  431. return baseCompile(template, extend({}, parserOptions, options, {
  432. nodeTransforms: [
  433. // ignore <script> and <tag>
  434. // this is not put inside DOMNodeTransforms because that list is used
  435. // by compiler-ssr to generate vnode fallback branches
  436. ignoreSideEffectTags,
  437. ...DOMNodeTransforms,
  438. ...(options.nodeTransforms || [])
  439. ],
  440. directiveTransforms: extend({}, DOMDirectiveTransforms, options.directiveTransforms || {}),
  441. transformHoist: null
  442. }));
  443. }
  444. function parse(template, options = {}) {
  445. return baseParse(template, extend({}, parserOptions, options));
  446. }
  447. 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 };